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:

  1. class MyClass(Base):
  2. __tablename__ = 'my_table'
  3. id = Column(Integer, primary_key=True)
  4. type = Column(String(50))
  5. alt = Column("some_alt", Integer)
  6.  
  7. __mapper_args__ = {
  8. 'polymorphic_on' : type
  9. }

Explicit use of mapper()is often referred to as classical mapping. The abovedeclarative example is equivalent in classical form to:

  1. my_table = Table("my_table", metadata,
  2. Column('id', Integer, primary_key=True),
  3. Column('type', String(50)),
  4. Column("some_alt", Integer)
  5. )
  6.  
  7. class MyClass(object):
  8. pass
  9.  
  10. mapper(MyClass, my_table,
  11. polymorphic_on=my_table.c.type,
  12. properties={
  13. 'alt':my_table.c.some_alt
  14. })

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 be None ifthis mapper inherits from another mapper using single-tableinheritance. When using Declarative, this argument isautomatically passed by the extension, based on whatis configured via the table argument or via theTable produced as a result of the tablenameand Column 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 methodQuery.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.

    • column_prefix

A string which will be prependedto the mapped attribute name when Columnobjects 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.

  1. -

concrete

If True, indicates this mapper should use concretetable inheritance with its parent mapper.

See the section Concrete Table Inheritance for an example.

  1. -

confirm_deleted_rows

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.

  1. -

eager_defaults

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.

  1. -

exclude_properties

A list or set of string column names tobe excluded from mapping.

See Mapping a Subset of Table Columns for an example.

  1. -

extension

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.

  1. -

include_properties

An inclusive list or set of string columnnames to map.

See Mapping a Subset of Table Columns for an example.

  1. -

inherits

A mapped class or the corresponding Mapperof one indicating a superclass to which this Mappershould 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

  1. -

inherit_condition – For joined table inheritance, a SQLexpression which willdefine how the two tables are joined; defaults to a natural joinbetween the two tables.

  1. -

inherit_foreign_keys – When inherit_condition is used andthe columns present are missing a ForeignKeyconfiguration, this parameter can be used to specify which columnsare “foreign”. In most cases can be left as None.

  1. -

legacy_is_orphan

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.

  1. -

non_primary

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

  1. -

order_by

A single Column or list of Columnobjects 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.

  1. -

passive_deletes

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 Trueon 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

  1. -

passive_updates

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

  1. -

polymorphic_load

  1. - Specifies polymorphic loading behavior
  2. -

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

Polymorphic Selectin Loading

  1. -

polymorphic_on

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:

  1. class Employee(Base):
  2. __tablename__ = 'employee'
  3.  
  4. id = Column(Integer, primary_key=True)
  5. discriminator = Column(String(50))
  6.  
  7. __mapper_args__ = {
  8. "polymorphic_on":discriminator,
  9. "polymorphic_identity":"employee"
  10. }

It may also be specifiedas a SQL expression, as in this example where weuse the case() construct to provide a conditionalapproach:

  1. class Employee(Base):
  2. __tablename__ = 'employee'
  3.  
  4. id = Column(Integer, primary_key=True)
  5. discriminator = Column(String(50))
  6.  
  7. __mapper_args__ = {
  8. "polymorphic_on":case([
  9. (discriminator == "EN", "engineer"),
  10. (discriminator == "MA", "manager"),
  11. ], else_="employee"),
  12. "polymorphic_identity":"employee"
  13. }

It may also refer to any attributeconfigured with column_property(), or to thestring name of one:

  1. class Employee(Base):
  2. __tablename__ = 'employee'
  3.  
  4. id = Column(Integer, primary_key=True)
  5. discriminator = Column(String(50))
  6. employee_type = column_property(
  7. case([
  8. (discriminator == "EN", "engineer"),
  9. (discriminator == "MA", "manager"),
  10. ], else_="employee")
  11. )
  12.  
  13. __mapper_args__ = {
  14. "polymorphic_on":employee_type,
  15. "polymorphic_identity":"employee"
  16. }

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:

  1. from sqlalchemy import event
  2. from sqlalchemy.orm import object_mapper
  3.  
  4. @event.listens_for(Employee, "init", propagate=True)
  5. def set_identity(instance, *arg, **kw):
  6. mapper = object_mapper(instance)
  7. instance.discriminator = mapper.polymorphic_identity

Where above, we assign the value of polymorphic_identityfor 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

  1. -

polymorphic_identity – Specifies the value whichidentifies this particular class as returned by thecolumn expression referred to by the polymorphic_onsetting. 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.

  1. -

properties – A dictionary mapping the string names of objectattributes to MapperProperty instances, which define thepersistence behavior of that attribute. Note that Columnobjects 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.

  1. -

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.

  1. -

version_id_col

A Columnthat 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.

  1. -

version_id_generator

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:

  1. def generate_version(version):
  2. 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

Server Side Version Counters

  1. -

with_polymorphic

A tuple in the form (<classes>,<selectable>) indicating the default style of “polymorphic”loading, that is, which tables are queried at once. isany single or list of mappers and/or classes indicating theinherited classes that should be loaded at once. The special value'*' may be used to indicate all descending classes should beloaded immediately. The second tuple argument indicates a selectable that will be used to query for multipleclasses.

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.UnmappedInstanceErrorif no mapping is configured.

This function is available via the inspection system as:

  1. 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:

  1. 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:

  • sqlalchemy.orm.clear_mappers()
  • Remove all mappers from all classes.

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 theSession.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.:

  1. >>> identity_key(MyClass, (1, 2))
  2. (<class '__main__.MyClass'>, (1, 2), None)
  1. - param class
  2. -

mapped class (must be a positional argument)

  1. - param ident
  2. -

primary key, may be a scalar or tuple argument.

  1. - param identity_token
  2. -

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.:

  1. >>> instance = MyClass(1, 2)
  2. >>> identity_key(instance=instance)
  3. (<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.

  1. - param instance
  2. -

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.:

  1. >>> row = engine.execute("select * from table where a=1 and b=2").first()
  2. >>> identity_key(MyClass, row=row)
  3. (<class '__main__.MyClass'>, (1, 2), None)
  1. - param class
  2. -

mapped class (must be a positional argument)

  1. - param row
  2. -

RowProxy row returned by a ResultProxy(must be given as a keyword arg)

  1. - param identity_token
  2. -

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 toTable 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:

  1. from sqlalchemy import inspect
  2.  
  3. mapper = inspect(MyClass)

A class which was mapped by the sqlalchemy.ext.declarativeextension will also have its mapper available via the mapperattribute.

  • 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.

  • addproperty(_key, prop)

  • 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

Mapper.attrs

  • 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 namecolumn. 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

Mapper.all_orm_descriptors

  • 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 Mapperobjects in the inheritance chain.

This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.

  • c = None
  • A synonym for columns.

  • cascadeiterator(type_, _state, halt_on=None)

  • Iterate each element and its mapper in an object graph,for all relationships that meet the given cascade rule.

    • Parameters
      • type_

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?.

  1. -

state – The lead InstanceState. child items will be processed perthe relationships defined for this object’s mapper.

  1. - Returns
  2. -

the method yields individual object instances.

See also

Cascades

How do I walk all objects that are related to a given object? - illustrates a generic function totraverse all objects without relying on cascades.

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 this Mapper.

This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.

See also

Mapper.attrs - namespace of all MapperPropertyobjects.

  • columns = None
  • A collection of Column or other scalar expressionobjects maintained by this Mapper.

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.

  • composites

  • Return a namespace of all CompositePropertyproperties maintained by this Mapper.

See also

Mapper.attrs - namespace of all MapperPropertyobjects.

  • concrete = None
  • Represent True if this Mapper 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 this Mapper has been configured.

This is a read only attribute determined during mapper construction.Behavior is undefined if directly modified.

See also

configure_mappers().

  • property entity
  • Part of the inspection API.

Returns self.class_.

  • getproperty(_key, _configure_mappers=True)
  • return a MapperProperty associated with the given key.

  • getproperty_by_column(_column)

  • Given a Column object, return theMapperProperty which maps this column.

  • identitykey_from_instance(_instance)

  • 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.

    • Parameters
    • primary_key – A list of values indicating the identifier.
  • identitykey_from_row(_row, identity_token=None, adapter=None)

  • Return an identity-map key for use in storing/retrieving anitem from the identity map.

    • Parameters
    • row – A RowProxy instance. The columns which aremapped by this Mapper should be locatable in the row,preferably via the Column object directly (as is the casewhen a select() construct is executed), or via string names ofthe form <tablename>_<colname>.
  • inherits = None

  • References the Mapper which this Mapperinherits 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.

  • isa(other)

  • Return True if the this mapper inherits from the given mapper.

  • property iterate_properties

  • return an iterator of all MapperProperty objects.

  • localtable = None_

  • The Selectable which this Mapper 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

persist_selectable.

  • property mapped_table

Deprecated since version 1.3: Use .persist_selectable

  • property mapper
  • Part of the inspection API.

Returns self.

  • nonprimary = None_
  • Represent True if this Mapper 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.

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.

local_table.

  • polymorphicidentity = None_
  • Represent an identifier which is matched against thepolymorphic_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 toMapper 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 this Mapper, 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 this Mapper.

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 Mapperfeatures 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.

  • primarykey_from_instance(_instance)
  • Return the list of primary key values for the giveninstance.

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).

  • relationships

  • A namespace of all RelationshipProperty propertiesmaintained by this Mapper.

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 MapperPropertyobjects.

  • property selectable
  • The select() construct this Mapper selects fromby default.

Normally, this is equivalent to persist_selectable, unlessthe with_polymorphic feature is in use, in which case thefull “polymorphic” selectable is returned.

  • self_and_descendants
  • The collection including this mapper and all descendant mappers.

This includes not just the immediately inheriting mappers butall their inheriting mappers as well.

  • single = None
  • Represent True if this Mapper 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.

See also

Mapper.attrs - namespace of all MapperPropertyobjects.

  • tables = None
  • An iterable containing the collection of Table objectswhich this Mapper is aware of.

If the mapper is mapped to a Join, or an Aliasrepresenting a Select, the individual Tableobjects 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.