Class Mapping API
sqlalchemy.orm.
mapper
(class__, _local_table=None, properties=None, primary_key=None, non_primary=False, inherits=None, inherit_condition=None, inherit_foreign_keys=None, extension=None, order_by=False, always_refresh=False, version_id_col=None, version_id_generator=None, polymorphic_on=None, polymorphicmap=None, polymorphic_identity=None, concrete=False, with_polymorphic=None, polymorphic_load=None, allow_partial_pks=True, batch=True, column_prefix=None, include_properties=None, exclude_properties=None, passive_updates=True, passive_deletes=False, confirm_deleted_rows=True, eager_defaults=False, legacy_is_orphan=False, compiledcache_size=100)- Return a new
Mapper
object.
This function is typically used behind the scenesvia the Declarative extension. When using Declarative,many of the usual mapper()
arguments are handledby the Declarative extension itself, including class
,localtable
, properties
, and inherits
.Other options are passed to mapper()
usingthe __mapper_args
class variable:
- class MyClass(Base):
- __tablename__ = 'my_table'
- id = Column(Integer, primary_key=True)
- type = Column(String(50))
- alt = Column("some_alt", Integer)
- __mapper_args__ = {
- 'polymorphic_on' : type
- }
Explicit use of mapper()
is often referred to as classical mapping. The abovedeclarative example is equivalent in classical form to:
- my_table = Table("my_table", metadata,
- Column('id', Integer, primary_key=True),
- Column('type', String(50)),
- Column("some_alt", Integer)
- )
- class MyClass(object):
- pass
- mapper(MyClass, my_table,
- polymorphic_on=my_table.c.type,
- properties={
- 'alt':my_table.c.some_alt
- })
See also
Classical Mappings - discussion of direct usage ofmapper()
- Parameters
class_ – The class to be mapped. When using Declarative,this argument is automatically passed as the declared classitself.
local_table – The
Table
or other selectableto which the class is mapped. May beNone
ifthis mapper inherits from another mapper using single-tableinheritance. When using Declarative, this argument isautomatically passed by the extension, based on whatis configured via thetable
argument or via theTable
produced as a result of thetablename
andColumn
arguments present.always_refresh – If True, all query operations for this mappedclass will overwrite all data within object instances that alreadyexist within the session, erasing any in-memory changes withwhatever information was loaded from the database. Usage of thisflag is highly discouraged; as an alternative, see the method
Query.populate_existing()
.allow_partial_pks – Defaults to True. Indicates that acomposite primary key with some NULL values should be considered aspossibly existing within the database. This affects whether amapper will assign an incoming row to an existing identity, as wellas if
Session.merge()
will check the database first for aparticular primary key value. A “partial primary key” can occur ifone has mapped to an OUTER JOIN, for example.batch – Defaults to
True
, indicating that save operationsof multiple entities can be batched together for efficiency.Setting to False indicatesthat an instance will be fully saved before saving the nextinstance. This is used in the extremely rare case that aMapperEvents
listener requires being calledin between individual row persistence operations.
A string which will be prependedto the mapped attribute name when Column
objects are automatically assigned as attributes to themapped class. Does not affect explicitly specifiedcolumn-based properties.
See the section Naming All Columns with a Prefix for an example.
-
If True, indicates this mapper should use concretetable inheritance with its parent mapper.
See the section Concrete Table Inheritance for an example.
-
defaults to True; when a DELETE occursof one more rows based on specific primary keys, a warning isemitted when the number of rows matched does not equal the numberof rows expected. This parameter may be set to False to handle thecase where database ON DELETE CASCADE rules may be deleting some ofthose rows automatically. The warning may be changed to anexception in a future release.
New in version 0.9.4: - addedmapper.confirm_deleted_rows
as well as conditionalmatched row checking on delete.
-
if True, the ORM will immediately fetch thevalue of server-generated default values after an INSERT or UPDATE,rather than leaving them as expired to be fetched on next access.This can be used for event schemes where the server-generated valuesare needed immediately before the flush completes. By default,this scheme will emit an individual SELECT
statement per rowinserted or updated, which note can add significant performanceoverhead. However, if thetarget database supports RETURNING, the default values willbe returned inline with the INSERT or UPDATE statement, which cangreatly enhance performance for an application that needs frequentaccess to just-generated server defaults.
See also
Fetching Server-Generated Defaults
Changed in version 0.9.0: The eager_defaults
option can nowmake use of RETURNING for backends which support it.
-
A list or set of string column names tobe excluded from mapping.
See Mapping a Subset of Table Columns for an example.
-
A MapperExtension
instance orlist of MapperExtension
instances which will be appliedto all operations by this Mapper
.
Deprecated since version 0.7: MapperExtension
is deprecated in favor of the MapperEvents
listener interface. The mapper.extension
parameter will be removed in a future release.
-
An inclusive list or set of string columnnames to map.
See Mapping a Subset of Table Columns for an example.
-
A mapped class or the corresponding Mapper
of one indicating a superclass to which this Mapper
should inherit from. The mapped class here must be a subclassof the other mapper’s class. When using Declarative, this argumentis passed automatically as a result of the natural classhierarchy of the declared classes.
See also
Mapping Class Inheritance Hierarchies
-
inherit_condition – For joined table inheritance, a SQLexpression which willdefine how the two tables are joined; defaults to a natural joinbetween the two tables.
-
inherit_foreign_keys – When inherit_condition
is used andthe columns present are missing a ForeignKey
configuration, this parameter can be used to specify which columnsare “foreign”. In most cases can be left as None
.
-
Boolean, defaults to False
.When True
, specifies that “legacy” orphan considerationis to be applied to objects mapped by this mapper, which meansthat a pending (that is, not persistent) object is auto-expungedfrom an owning Session
only when it is de-associatedfrom all parents that specify a delete-orphan
cascade towardsthis mapper. The new default behavior is that the object isauto-expunged when it is de-associated with any of its parentsthat specify delete-orphan
cascade. This behavior is moreconsistent with that of a persistent object, and allows behavior tobe consistent in more scenarios independently of whether or not anorphanable object has been flushed yet or not.
See the change note and example at The consideration of a “pending” object as an “orphan” has been made more aggressivefor more detail on this change.
-
Specify that this Mapper
is in additionto the “primary” mapper, that is, the one used for persistence.The Mapper
created here may be used for ad-hocmapping of the class to an alternate selectable, for loadingonly.
Deprecated since version 1.3: The mapper.non_primary
parameter is deprecated, and will be removed in a future release. The functionality of non primary mappers is now better suited using the AliasedClass
construct, which can also be used as the target of a relationship()
in 1.3.
Mapper.non_primary
is not an often used option, butis useful in some specific relationship()
cases.
See also
relationship_non_primary_mapper
-
A single Column
or list of Column
objects for which selection operations should use as the defaultordering for entities. By default mappers have no pre-definedordering.
Deprecated since version 1.1: The mapper.order_by
parameter is deprecated, and will be removed in a future release. Use Query.order_by()
to determine the ordering of a result set.
-
Indicates DELETE behavior of foreign keycolumns when a joined-table inheritance entity is being deleted.Defaults to False
for a base mapper; for an inheriting mapper,defaults to False
unless the value is set to True
on the superclass mapper.
When True
, it is assumed that ON DELETE CASCADE is configuredon the foreign key relationships that link this mapper’s tableto its superclass table, so that when the unit of work attemptsto delete the entity, it need only emit a DELETE statement for thesuperclass table, and not this table.
When False
, a DELETE statement is emitted for this mapper’stable individually. If the primary key attributes local to thistable are unloaded, then a SELECT must be emitted in order tovalidate these attributes; note that the primary key columnsof a joined-table subclass are not part of the “primary key” ofthe object as a whole.
Note that a value of True
is always forced onto thesubclass mappers; that is, it’s not possible for a superclassto specify passive_deletes without this taking effect forall subclass mappers.
New in version 1.1.
See also
Using Passive Deletes - description of similar feature asused with relationship()
mapper.passive_updates
- supporting ON UPDATECASCADE for joined-table inheritance mappers
-
Indicates UPDATE behavior of foreign keycolumns when a primary key column changes on a joined-tableinheritance mapping. Defaults to True
.
When True, it is assumed that ON UPDATE CASCADE is configured onthe foreign key in the database, and that the database will handlepropagation of an UPDATE from a source column to dependent columnson joined-table rows.
When False, it is assumed that the database does not enforcereferential integrity and will not be issuing its own CASCADEoperation for an update. The unit of work process willemit an UPDATE statement for the dependent columns during aprimary key change.
See also
Mutable Primary Keys / Update Cascades - description of a similar feature asused with relationship()
mapper.passive_deletes
- supporting ON DELETECASCADE for joined-table inheritance mappers
-
- Specifies “polymorphic loading” behavior
-
for a subclass in an inheritance hierarchy (joined and singletable inheritance only). Valid values are:
“‘inline’” - specifies this class should be part of the“with_polymorphic” mappers, e.g. its columns will be includedin a SELECT query against the base.
“‘selectin’” - specifies that when instances of this classare loaded, an additional SELECT will be emitted to retrievethe columns specific to this subclass. The SELECT usesIN to fetch multiple subclasses at once.
New in version 1.2.
See also
Setting with_polymorphic at mapper configuration time
-
Specifies the column, attribute, orSQL expression used to determine the target class for anincoming row, when inheriting classes are present.
This value is commonly a Column
object that’spresent in the mapped Table
:
- class Employee(Base):
- __tablename__ = 'employee'
- id = Column(Integer, primary_key=True)
- discriminator = Column(String(50))
- __mapper_args__ = {
- "polymorphic_on":discriminator,
- "polymorphic_identity":"employee"
- }
It may also be specifiedas a SQL expression, as in this example where weuse the case()
construct to provide a conditionalapproach:
- class Employee(Base):
- __tablename__ = 'employee'
- id = Column(Integer, primary_key=True)
- discriminator = Column(String(50))
- __mapper_args__ = {
- "polymorphic_on":case([
- (discriminator == "EN", "engineer"),
- (discriminator == "MA", "manager"),
- ], else_="employee"),
- "polymorphic_identity":"employee"
- }
It may also refer to any attributeconfigured with column_property()
, or to thestring name of one:
- class Employee(Base):
- __tablename__ = 'employee'
- id = Column(Integer, primary_key=True)
- discriminator = Column(String(50))
- employee_type = column_property(
- case([
- (discriminator == "EN", "engineer"),
- (discriminator == "MA", "manager"),
- ], else_="employee")
- )
- __mapper_args__ = {
- "polymorphic_on":employee_type,
- "polymorphic_identity":"employee"
- }
When setting polymorphic_on
to reference anattribute or expression that’s not present in thelocally mapped Table
, yet the valueof the discriminator should be persisted to the database,the value of thediscriminator is not automatically set on newinstances; this must be handled by the user,either through manual means or via event listeners.A typical approach to establishing such a listenerlooks like:
- from sqlalchemy import event
- from sqlalchemy.orm import object_mapper
- @event.listens_for(Employee, "init", propagate=True)
- def set_identity(instance, *arg, **kw):
- mapper = object_mapper(instance)
- instance.discriminator = mapper.polymorphic_identity
Where above, we assign the value of polymorphic_identity
for the mapped class to the discriminator
attribute,thus persisting the value to the discriminator
columnin the database.
Warning
Currently, only one discriminator column may be set, typicallyon the base-most class in the hierarchy. “Cascading” polymorphiccolumns are not yet supported.
See also
Mapping Class Inheritance Hierarchies
-
polymorphic_identity – Specifies the value whichidentifies this particular class as returned by thecolumn expression referred to by the polymorphic_on
setting. As rows are received, the value correspondingto the polymorphic_on
column expression is comparedto this value, indicating which subclass shouldbe used for the newly reconstructed object.
-
properties – A dictionary mapping the string names of objectattributes to MapperProperty
instances, which define thepersistence behavior of that attribute. Note that Column
objects present inthe mapped Table
are automatically placed intoColumnProperty
instances upon mapping, unless overridden.When using Declarative, this argument is passed automatically,based on all those MapperProperty
instances declaredin the declared class body.
-
primary_key – A list of Column
objects which definethe primary key to be used against this mapper’s selectable unit.This is normally simply the primary key of the local_table
, butcan be overridden here.
-
A Column
that will be used to keep a running version id of rowsin the table. This is used to detect concurrent updates orthe presence of stale data in a flush. The methodology is todetect if an UPDATE statement does not match the last knownversion id, aStaleDataError
exception isthrown.By default, the column must be of Integer
type,unless version_id_generator
specifies an alternative versiongenerator.
See also
Configuring a Version Counter - discussion of version countingand rationale.
-
Define how new version ids shouldbe generated. Defaults to None
, which indicates thata simple integer counting scheme be employed. To provide a customversioning scheme, provide a callable function of the form:
- def generate_version(version):
- return next_version
Alternatively, server-side versioning functions such as triggers,or programmatic versioning schemes outside of the version idgenerator may be used, by specifying the value False
.Please see Server Side Version Counters for a discussionof important points when using this option.
New in version 0.9.0: version_id_generator
supportsserver-side version number generation.
See also
Custom Version Counters / Types
-
A tuple in the form (<classes>,<selectable>)
indicating the default style of “polymorphic”loading, that is, which tables are queried at once. '*'
may be used to indicate all descending classes should beloaded immediately. The second tuple argument
See also
Using with_polymorphic - discussion of polymorphic queryingtechniques.
sqlalchemy.orm.
objectmapper
(_instance)- Given an object, return the primary Mapper associated with the objectinstance.
Raises sqlalchemy.orm.exc.UnmappedInstanceError
if no mapping is configured.
This function is available via the inspection system as:
- inspect(instance).mapper
Using the inspection system will raisesqlalchemy.exc.NoInspectionAvailable
if the instance isnot part of a mapping.
sqlalchemy.orm.
classmapper
(class_, _configure=True)- Given a class, return the primary
Mapper
associatedwith the key.
Raises UnmappedClassError
if no mapping is configuredon the given class, or ArgumentError
if a non-classobject is passed.
Equivalent functionality is available via the inspect()
function as:
- inspect(some_mapped_class)
Using the inspection system will raisesqlalchemy.exc.NoInspectionAvailable
if the class is not mapped.
sqlalchemy.orm.
configure_mappers
()- Initialize the inter-mapper relationships of all mappers thathave been constructed thus far.
This function can be called any number of times, but inmost cases is invoked automatically, the first time mappings are used,as well as whenever mappings are used and additional not-yet-configuredmappers have been constructed.
Points at which this occur include when a mapped class is instantiatedinto an instance, as well as when the Session.query()
methodis used.
The configure_mappers()
function provides several event hooksthat can be used to augment its functionality. These methods include:
MapperEvents.before_configured()
- called once beforeconfigure_mappers()
does any work; this can be used to establishadditional options, properties, or related mappings before the operationproceeds.MapperEvents.mapper_configured()
- called as each individualMapper
is configured within the process; will include allmapper state except for backrefs set up by other mappers that are stillto be configured.MapperEvents.after_configured()
- called once afterconfigure_mappers()
is complete; at this stage, allMapper
objects that are known to SQLAlchemy will be fullyconfigured. Note that the calling application may still have othermappings that haven’t been produced yet, such as if they are in modulesas yet unimported.
This function removes all instrumentation from classes and disposesof their associated mappers. Once called, the classes are unmappedand can be later re-mapped with new mappers.
clear_mappers()
is not for normal use, as there is literally novalid usage for it outside of very specific testing scenarios. Normally,mappers are permanent structural components of user-defined classes, andare never discarded independently of their class. If a mapped classitself is garbage collected, its mapper is automatically disposed of aswell. As such, clear_mappers()
is only for usage in test suitesthat re-use the same classes with different mappings, which is itself anextremely rare use case - the only such use case is in fact SQLAlchemy’sown test suite, and possibly the test suites of other ORM extensionlibraries which intend to test various combinations of mapper constructionupon a fixed set of classes.
sqlalchemy.orm.util.
identitykey
(args, *kwargs_)- Generate “identity key” tuples, as are used as keys in the
Session.identity_map
dictionary.
This function has several call styles:
identity_key(class, ident, identity_token=token)
This form receives a mapped class and a primary key scalar ortuple as an argument.
E.g.:
- >>> identity_key(MyClass, (1, 2))
- (<class '__main__.MyClass'>, (1, 2), None)
- param class
-
mapped class (must be a positional argument)
- param ident
-
primary key, may be a scalar or tuple argument.
- param identity_token
-
optional identity token
New in version 1.2: added identity_token
identity_key(instance=instance)
This form will produce the identity key for a given instance. Theinstance need not be persistent, only that its primary key attributesare populated (else the key will contain None
for those missingvalues).
E.g.:
- >>> instance = MyClass(1, 2)
- >>> identity_key(instance=instance)
- (<class '__main__.MyClass'>, (1, 2), None)
In this form, the given instance is ultimately run thoughMapper.identity_key_from_instance()
, which will have theeffect of performing a database check for the corresponding rowif the object is expired.
- param instance
-
object instance (must be given as a keyword arg)
identity_key(class, row=row, identity_token=token)
This form is similar to the class/tuple form, except is passed adatabase result row as a RowProxy
object.
E.g.:
- >>> row = engine.execute("select * from table where a=1 and b=2").first()
- >>> identity_key(MyClass, row=row)
- (<class '__main__.MyClass'>, (1, 2), None)
- param class
-
mapped class (must be a positional argument)
- param row
-
RowProxy
row returned by a ResultProxy
(must be given as a keyword arg)
- param identity_token
-
optional identity token
New in version 1.2: added identity_token
sqlalchemy.orm.util.
polymorphicunion
(_table_map, typecolname, aliasname='p_union', cast_nulls=True)- Create a
UNION
statement used by a polymorphic mapper.
See Concrete Table Inheritance for an example of howthis is used.
- Parameters
table_map – mapping of polymorphic identities to
Table
objects.typecolname – string name of a “discriminator” column, which will bederived from the query, producing the polymorphic identity foreach row. If
None
, no polymorphic discriminator is generated.aliasname – name of the
alias()
construct generated.cast_nulls – if True, non-existent columns, which are representedas labeled NULLs, will be passed into CAST. This is a legacy behaviorthat is problematic on some backends such as Oracle - in which case itcan be set to False.
- class
sqlalchemy.orm.mapper.
Mapper
(class__, _local_table=None, properties=None, primary_key=None, non_primary=False, inherits=None, inherit_condition=None, inherit_foreign_keys=None, extension=None, order_by=False, always_refresh=False, version_id_col=None, version_id_generator=None, polymorphic_on=None, polymorphicmap=None, polymorphic_identity=None, concrete=False, with_polymorphic=None, polymorphic_load=None, allow_partial_pks=True, batch=True, column_prefix=None, include_properties=None, exclude_properties=None, passive_updates=True, passive_deletes=False, confirm_deleted_rows=True, eager_defaults=False, legacy_is_orphan=False, compiledcache_size=100) - Bases:
sqlalchemy.orm.base.InspectionAttr
Define the correlation of class attributes to database tablecolumns.
The Mapper
object is instantiated using themapper()
function. For informationabout instantiating new Mapper
objects, seethat function’s documentation.
When mapper()
is usedexplicitly to link a user defined class with tablemetadata, this is referred to as classical mapping.Modern SQLAlchemy usage tends to favor thesqlalchemy.ext.declarative
extension for classconfiguration, whichmakes usage of mapper()
behind the scenes.
Given a particular class known to be mapped by the ORM,the Mapper
which maintains it can be acquiredusing the inspect()
function:
- from sqlalchemy import inspect
- mapper = inspect(MyClass)
A class which was mapped by the sqlalchemy.ext.declarative
extension will also have its mapper available via the mapper
attribute.
init
(class__, _local_table=None, properties=None, primary_key=None, non_primary=False, inherits=None, inherit_condition=None, inherit_foreign_keys=None, extension=None, order_by=False, always_refresh=False, version_id_col=None, version_id_generator=None, polymorphic_on=None, polymorphicmap=None, polymorphic_identity=None, concrete=False, with_polymorphic=None, polymorphic_load=None, allow_partial_pks=True, batch=True, column_prefix=None, include_properties=None, exclude_properties=None, passive_updates=True, passive_deletes=False, confirm_deleted_rows=True, eager_defaults=False, legacy_is_orphan=False, compiledcache_size=100)- Construct a new
Mapper
object.
This constructor is mirrored as a public API function; see mapper()
for a full usage and argument description.
addproperties
(_dict_of_properties)Add the given dictionary of properties to this mapper,using add_property.
- Add an individual MapperProperty to this mapper.
If the mapper has not been configured yet, just adds theproperty to the initial properties dictionary sent to theconstructor. If this Mapper has already been configured, thenthe given MapperProperty is configured immediately.
all_orm_descriptors
- A namespace of all
InspectionAttr
attributes associatedwith the mapped class.
These attributes are in all cases Python descriptorsassociated with the mapped class or its superclasses.
This namespace includes attributes that are mapped to the classas well as attributes declared by extension modules.It includes any Python descriptor type that inherits fromInspectionAttr
. This includesQueryableAttribute
, as well as extension types such ashybrid_property
, hybrid_method
andAssociationProxy
.
To distinguish between mapped attributes and extension attributes,the attribute InspectionAttr.extension_type
will referto a constant that distinguishes between different extension types.
When dealing with a QueryableAttribute
, theQueryableAttribute.property
attribute refers to theMapperProperty
property, which is what you get whenreferring to the collection of mapped properties viaMapper.attrs
.
Warning
The Mapper.all_orm_descriptors
accessor namespace is aninstance of OrderedProperties
. This isa dictionary-like object which includes a small number ofnamed methods such as OrderedProperties.items()
and OrderedProperties.values()
. Whenaccessing attributes dynamically, favor using the dict-accessscheme, e.g. mapper.all_orm_descriptors[somename]
overgetattr(mapper.all_orm_descriptors, somename)
to avoid namecollisions.
See also
attrs
- A namespace of all
MapperProperty
objectsassociated this mapper.
This is an object that provides each property based onits key name. For instance, the mapper for aUser
class which has User.name
attribute wouldprovide mapper.attrs.name
, which would be theColumnProperty
representing the name
column. The namespace object can also be iterated,which would yield each MapperProperty
.
Mapper
has several pre-filtered viewsof this attribute which limit the types of propertiesreturned, including synonyms
, column_attrs
,relationships
, and composites
.
Warning
The Mapper.attrs
accessor namespace is aninstance of OrderedProperties
. This isa dictionary-like object which includes a small number ofnamed methods such as OrderedProperties.items()
and OrderedProperties.values()
. Whenaccessing attributes dynamically, favor using the dict-accessscheme, e.g. mapper.attrs[somename]
overgetattr(mapper.attrs, somename)
to avoid name collisions.
See also
basemapper
= None_- The base-most
Mapper
in an inheritance chain.
In a non-inheriting scenario, this attribute will always be thisMapper
. In an inheritance scenario, it referencesthe Mapper
which is parent to all other Mapper
objects in the inheritance chain.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
c
= NoneA synonym for
columns
.Iterate each element and its mapper in an object graph,for all relationships that meet the given cascade rule.
The name of the cascade rule (i.e. "save-update"
, "delete"
,etc.).
Note
the "all"
cascade is not accepted here. For a genericobject traversal function, see How do I walk all objects that are related to a given object?.
-
state – The lead InstanceState. child items will be processed perthe relationships defined for this object’s mapper.
- Returns
-
the method yields individual object instances.
See also
How do I walk all objects that are related to a given object? - illustrates a generic function totraverse all objects without relying on cascades.
class
= None[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.mapper.Mapper.class)- The Python class which this
Mapper
maps.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
classmanager
= None_- The
ClassManager
which maintains event listenersand class-bound descriptors for thisMapper
.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
column_attrs
- Return a namespace of all
ColumnProperty
properties maintained by thisMapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
The collection behaves the same as that of the c
attribute onany Table
object, except that only those columns included inthis mapping are present, and are keyed based on the attribute namedefined in the mapping, not necessarily the key
attribute of theColumn
itself. Additionally, scalar expressions mappedby column_property()
are also present here.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
commonparent
(_other)Return true if the given mapper shares acommon inherited parent as this mapper.
- Return a namespace of all
CompositeProperty
properties maintained by thisMapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
concrete
= None- Represent
True
if thisMapper
is a concreteinheritance mapper.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
configured
= None- Represent
True
if thisMapper
has been configured.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
See also
Returns self.class_.
getproperty
(_key, _configure_mappers=True)return a MapperProperty associated with the given key.
Given a
Column
object, return theMapperProperty
which maps this column.- Return the identity key for the given instance, based onits primary key attributes.
If the instance’s state is expired, calling this methodwill result in a database check to see if the object has been deleted.If the row no longer exists,ObjectDeletedError
is raised.
This value is typically also found on the instance state under theattribute name key.
identitykey_from_primary_key
(_primary_key, identity_token=None)Return an identity-map key for use in storing/retrieving anitem from an identity map.
identitykey_from_row
(_row, identity_token=None, adapter=None)Return an identity-map key for use in storing/retrieving anitem from the identity map.
- References the
Mapper
which thisMapper
inherits from, if any.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
ismapper
= True_Part of the inspection API.
Return True if the this mapper inherits from the given mapper.
return an iterator of all MapperProperty objects.
- The
Selectable
which thisMapper
manages.
Typically is an instance of Table
or Alias
.May also be None
.
The “local” table is theselectable that the Mapper
is directly responsible formanaging from an attribute access and flush perspective. Fornon-inheriting mappers, the local table is the same as the“mapped” table. For joined-table inheritance mappers, local_tablewill be the particular sub-table of the overall “join” whichthis Mapper
represents. If this mapper is asingle-table inheriting mapper, local_table will be None
.
See also
Deprecated since version 1.3: Use .persist_selectable
Returns self.
nonprimary
= None_- Represent
True
if thisMapper
is a “non-primary”mapper, e.g. a mapper that is used only to select rows but not forpersistence management.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
persistselectable
= None_- The
Selectable
to which thisMapper
is mapped.
Typically an instance of Table
, Join
, orAlias
.
The Mapper.persist_selectable
is separate fromMapper.selectable
in that the former represents columnsthat are mapped on this class or its superclasses, whereas thelatter may be a “polymorphic” selectable that contains additional columnswhich are in fact mapped on subclasses only.
“persist selectable” is the “thing the mapper writes to” and“selectable” is the “thing the mapper selects from”.
Mapper.persist_selectable
is also separate fromMapper.local_table
, which represents the set of columns thatare locally mapped on this class directly.
See also
selectable
.
polymorphicidentity
= None_- Represent an identifier which is matched against the
polymorphic_on
column during result row loading.
Used only with inheritance, this object can be of any type which iscomparable to the type of column represented bypolymorphic_on
.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
polymorphic_iterator
()- Iterate through the collection including this mapper andall descendant mappers.
This includes not just the immediately inheriting mappers butall their inheriting mappers as well.
To iterate through an entire hierarchy, usemapper.base_mapper.polymorphic_iterator()
.
polymorphicmap
= None_- A mapping of “polymorphic identity” identifiers mapped to
Mapper
instances, within an inheritance scenario.
The identifiers can be of any type which is comparable to thetype of column represented by polymorphic_on
.
An inheritance chain of mappers will all reference the samepolymorphic map object. The object is used to correlate incomingresult rows to target mappers.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
polymorphicon
= None_- The
Column
or SQL expression specified as thepolymorphic_on
argumentfor thisMapper
, within an inheritance scenario.
This attribute is normally a Column
instance butmay also be an expression, such as one derived fromcast()
.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
primarykey
= None_- An iterable containing the collection of
Column
objectswhich comprise the ‘primary key’ of the mapped table, from theperspective of thisMapper
.
This list is against the selectable in persist_selectable
.In the case of inheriting mappers, some columns may be managed by asuperclass mapper. For example, in the case of a Join
, theprimary key is determined by all of the primary key columns across alltables referenced by the Join
.
The list is also not necessarily the same as the primary key columncollection associated with the underlying tables; the Mapper
features a primary_key
argument that can override what theMapper
considers as primary key columns.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
If the instance’s state is expired, calling this methodwill result in a database check to see if the object has been deleted.If the row no longer exists,ObjectDeletedError
is raised.
primary_mapper
()Return the primary mapper corresponding to this mapper’s class key(class).
- A namespace of all
RelationshipProperty
propertiesmaintained by thisMapper
.
Warning
the Mapper.relationships
accessor namespace is aninstance of OrderedProperties
. This isa dictionary-like object which includes a small number ofnamed methods such as OrderedProperties.items()
and OrderedProperties.values()
. Whenaccessing attributes dynamically, favor using the dict-accessscheme, e.g. mapper.relationships[somename]
overgetattr(mapper.relationships, somename)
to avoid namecollisions.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
Normally, this is equivalent to persist_selectable
, unlessthe with_polymorphic
feature is in use, in which case thefull “polymorphic” selectable is returned.
This includes not just the immediately inheriting mappers butall their inheriting mappers as well.
single
= None- Represent
True
if thisMapper
is a single tableinheritance mapper.
local_table
will be None
if this flag is set.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
synonyms
- Return a namespace of all
SynonymProperty
properties maintained by thisMapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
If the mapper is mapped to a Join
, or an Alias
representing a Select
, the individual Table
objects that comprise the full construct will be represented here.
This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.
validators
= None- An immutable dictionary of attributes which have been decoratedusing the
validates()
decorator.
The dictionary contains string attribute names as keysmapped to the actual validation method.
with_polymorphic_mappers
- The list of
Mapper
objects included in thedefault “polymorphic” query.