Class Mapping API¶
| Object Name | Description |
|---|---|
class_mapper(class_[, configure]) |
Given a class, return the primary |
Remove all mappers from all classes. |
|
Initialize the inter-mapper relationships of all mappers that have been constructed thus far. |
|
identity_key(*args, **kwargs) |
|
mapper(class_[, local_table, properties, primary_key, ...]) |
Return a new |
Define the correlation of class attributes to database table columns. |
|
object_mapper(instance) |
Given an object, return the primary Mapper associated with the object instance. |
polymorphic_union(table_map, typecolname[, aliasname, cast_nulls]) |
Create a |
- function 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, _polymorphic_map=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, _compiled_cache_size=100)¶
Return a new
Mapperobject.This function is typically used behind the scenes via the Declarative extension. When using Declarative, many of the usual
mapper()arguments are handled by the Declarative extension itself, includingclass_,local_table,properties, andinherits. Other options are passed tomapper()using the__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 above declarative 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 of
mapper()- Parameters:
class_ – The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself.
local_table – The
Tableor other selectable to which the class is mapped. May beNoneif this mapper inherits from another mapper using single-table inheritance. When using Declarative, this argument is automatically passed by the extension, based on what is configured via the__table__argument or via theTableproduced as a result of the__tablename__andColumnarguments present.always_refresh – If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method
Query.populate_existing().allow_partial_pks – Defaults to True. Indicates that a composite primary key with some NULL values should be considered as possibly existing within the database. This affects whether a mapper will assign an incoming row to an existing identity, as well as if
Session.merge()will check the database first for a particular primary key value. A “partial primary key” can occur if one has mapped to an OUTER JOIN, for example.batch – Defaults to
True, indicating that save operations of multiple entities can be batched together for efficiency. Setting to False indicates that an instance will be fully saved before saving the next instance. This is used in the extremely rare case that aMapperEventslistener requires being called in between individual row persistence operations.column_prefix –
A string which will be prepended to the mapped attribute name when
Columnobjects are automatically assigned as attributes to the mapped class. Does not affect explicitly specified column-based properties.See the section Naming All Columns with a Prefix for an example.
concrete –
If True, indicates this mapper should use concrete table inheritance with its parent mapper.
See the section Concrete Table Inheritance for an example.
confirm_deleted_rows –
defaults to True; when a DELETE occurs of one more rows based on specific primary keys, a warning is emitted when the number of rows matched does not equal the number of rows expected. This parameter may be set to False to handle the case where database ON DELETE CASCADE rules may be deleting some of those rows automatically. The warning may be changed to an exception in a future release.
New in version 0.9.4: - added
mapper.confirm_deleted_rowsas well as conditional matched row checking on delete.eager_defaults –
if True, the ORM will immediately fetch the value 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 values are needed immediately before the flush completes. By default, this scheme will emit an individual
SELECTstatement per row inserted or updated, which note can add significant performance overhead. However, if the target database supports RETURNING, the default values will be returned inline with the INSERT or UPDATE statement, which can greatly enhance performance for an application that needs frequent access to just-generated server defaults.See also
Changed in version 0.9.0: The
eager_defaultsoption can now make use of RETURNING for backends which support it.exclude_properties –
A list or set of string column names to be excluded from mapping.
See Mapping a Subset of Table Columns for an example.
extension –
A
MapperExtensioninstance or list ofMapperExtensioninstances which will be applied to all operations by thisMapper.Deprecated since version 0.7:
MapperExtensionis deprecated in favor of theMapperEventslistener interface. Themapper.extensionparameter will be removed in a future release.include_properties –
An inclusive list or set of string column names to map.
See Mapping a Subset of Table Columns for an example.
inherits –
A mapped class or the corresponding
Mapperof one indicating a superclass to which thisMappershould inherit from. The mapped class here must be a subclass of the other mapper’s class. When using Declarative, this argument is passed automatically as a result of the natural class hierarchy of the declared classes.inherit_condition – For joined table inheritance, a SQL expression which will define how the two tables are joined; defaults to a natural join between the two tables.
inherit_foreign_keys – When
inherit_conditionis used and the columns present are missing aForeignKeyconfiguration, this parameter can be used to specify which columns are “foreign”. In most cases can be left asNone.legacy_is_orphan –
Boolean, defaults to
False. WhenTrue, specifies that “legacy” orphan consideration is to be applied to objects mapped by this mapper, which means that a pending (that is, not persistent) object is auto-expunged from an owningSessiononly when it is de-associated from all parents that specify adelete-orphancascade towards this mapper. The new default behavior is that the object is auto-expunged when it is de-associated with any of its parents that specifydelete-orphancascade. This behavior is more consistent with that of a persistent object, and allows behavior to be consistent in more scenarios independently of whether or not an orphan 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 aggressive for more detail on this change.
non_primary –
Specify that this
Mapperis in addition to the “primary” mapper, that is, the one used for persistence. TheMappercreated here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only.Deprecated since version 1.3: The
mapper.non_primaryparameter is deprecated, and will be removed in a future release. The functionality of non primary mappers is now better suited using theAliasedClassconstruct, which can also be used as the target of arelationship()in 1.3.Mapper.non_primaryis not an often used option, but is useful in some specificrelationship()cases.See also
order_by –
A single
Columnor list ofColumnobjects for which selection operations should use as the default ordering for entities. By default mappers have no pre-defined ordering.Deprecated since version 1.1: The
mapper.order_byparameter is deprecated, and will be removed in a future release. UseQuery.order_by()to determine the ordering of a result set.passive_deletes –
Indicates DELETE behavior of foreign key columns when a joined-table inheritance entity is being deleted. Defaults to
Falsefor a base mapper; for an inheriting mapper, defaults toFalseunless the value is set toTrueon the superclass mapper.When
True, it is assumed that ON DELETE CASCADE is configured on the foreign key relationships that link this mapper’s table to its superclass table, so that when the unit of work attempts to delete the entity, it need only emit a DELETE statement for the superclass table, and not this table.When
False, a DELETE statement is emitted for this mapper’s table individually. If the primary key attributes local to this table are unloaded, then a SELECT must be emitted in order to validate these attributes; note that the primary key columns of a joined-table subclass are not part of the “primary key” of the object as a whole.Note that a value of
Trueis always forced onto the subclass mappers; that is, it’s not possible for a superclass to specify passive_deletes without this taking effect for all subclass mappers.New in version 1.1.
See also
Using foreign key ON DELETE cascade with ORM relationships - description of similar feature as used with
relationship()mapper.passive_updates- supporting ON UPDATE CASCADE for joined-table inheritance mapperspassive_updates –
Indicates UPDATE behavior of foreign key columns when a primary key column changes on a joined-table inheritance mapping. Defaults to
True.When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent columns on joined-table rows.
When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The unit of work process will emit an UPDATE statement for the dependent columns during a primary key change.
See also
Mutable Primary Keys / Update Cascades - description of a similar feature as used with
relationship()mapper.passive_deletes- supporting ON DELETE CASCADE for joined-table inheritance mapperspolymorphic_load –
- Specifies “polymorphic loading” behavior
for a subclass in an inheritance hierarchy (joined and single table inheritance only). Valid values are:
“‘inline’” - specifies this class should be part of the “with_polymorphic” mappers, e.g. its columns will be included in a SELECT query against the base.
“‘selectin’” - specifies that when instances of this class are loaded, an additional SELECT will be emitted to retrieve the columns specific to this subclass. The SELECT uses IN to fetch multiple subclasses at once.
New in version 1.2.
polymorphic_on –
Specifies the column, attribute, or SQL expression used to determine the target class for an incoming row, when inheriting classes are present.
This value is commonly a
Columnobject that’s present in the mappedTable: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 specified as a SQL expression, as in this example where we use the
case()construct to provide a conditional approach: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 attribute configured with
column_property(), or to the string 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_onto reference an attribute or expression that’s not present in the locally mappedTable, yet the value of the discriminator should be persisted to the database, the value of the discriminator is not automatically set on new instances; this must be handled by the user, either through manual means or via event listeners. A typical approach to establishing such a listener looks 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_identityfor the mapped class to thediscriminatorattribute, thus persisting the value to thediscriminatorcolumn in the database.Warning
Currently, only one discriminator column may be set, typically on the base-most class in the hierarchy. “Cascading” polymorphic columns are not yet supported.
polymorphic_identity – Specifies the value which identifies this particular class as returned by the column expression referred to by the
polymorphic_onsetting. As rows are received, the value corresponding to thepolymorphic_oncolumn expression is compared to this value, indicating which subclass should be used for the newly reconstructed object.properties – A dictionary mapping the string names of object attributes to
MapperPropertyinstances, which define the persistence behavior of that attribute. Note thatColumnobjects present in the mappedTableare automatically placed intoColumnPropertyinstances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all thoseMapperPropertyinstances declared in the declared class body.primary_key – A list of
Columnobjects which define the primary key to be used against this mapper’s selectable unit. This is normally simply the primary key of thelocal_table, but can be overridden here.version_id_col –
A
Columnthat will be used to keep a running version id of rows in the table. This is used to detect concurrent updates or the presence of stale data in a flush. The methodology is to detect if an UPDATE statement does not match the last known version id, aStaleDataErrorexception is thrown. By default, the column must be ofIntegertype, unlessversion_id_generatorspecifies an alternative version generator.See also
Configuring a Version Counter - discussion of version counting and rationale.
version_id_generator –
Define how new version ids should be generated. Defaults to
None, which indicates that a simple integer counting scheme be employed. To provide a custom versioning 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 id generator may be used, by specifying the value
False. Please see Server Side Version Counters for a discussion of important points when using this option.New in version 0.9.0:
version_id_generatorsupports server-side version number generation.with_polymorphic –
A tuple in the form
(<classes>, <selectable>)indicating the default style of “polymorphic” loading, that is, which tables are queried at once. <classes> is any single or list of mappers and/or classes indicating the inherited classes that should be loaded at once. The special value'*'may be used to indicate all descending classes should be loaded immediately. The second tuple argument <selectable> indicates a selectable that will be used to query for multiple classes.See also
Using with_polymorphic - discussion of polymorphic querying techniques.
- function sqlalchemy.orm.object_mapper(instance)¶
Given an object, return the primary Mapper associated with the object instance.
Raises
sqlalchemy.orm.exc.UnmappedInstanceErrorif no mapping is configured.This function is available via the inspection system as:
inspect(instance).mapper
Using the inspection system will raise
sqlalchemy.exc.NoInspectionAvailableif the instance is not part of a mapping.
- function sqlalchemy.orm.class_mapper(class_, configure=True)¶
Given a class, return the primary
Mapperassociated with the key.Raises
UnmappedClassErrorif no mapping is configured on the given class, orArgumentErrorif a non-class object is passed.Equivalent functionality is available via the
inspect()function as:inspect(some_mapped_class)
Using the inspection system will raise
sqlalchemy.exc.NoInspectionAvailableif the class is not mapped.
- function sqlalchemy.orm.configure_mappers()¶
Initialize the inter-mapper relationships of all mappers that have been constructed thus far.
This function can be called any number of times, but in most cases is invoked automatically, the first time mappings are used, as well as whenever mappings are used and additional not-yet-configured mappers have been constructed.
Points at which this occur include when a mapped class is instantiated into an instance, as well as when the
Session.query()method is used.The
configure_mappers()function provides several event hooks that 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 establish additional options, properties, or related mappings before the operation proceeds.MapperEvents.mapper_configured()- called as each individualMapperis configured within the process; will include all mapper state except for backrefs set up by other mappers that are still to be configured.MapperEvents.after_configured()- called once afterconfigure_mappers()is complete; at this stage, allMapperobjects that are known to SQLAlchemy will be fully configured. Note that the calling application may still have other mappings that haven’t been produced yet, such as if they are in modules as yet unimported.
- function sqlalchemy.orm.clear_mappers()¶
Remove all mappers from all classes.
This function removes all instrumentation from classes and disposes of their associated mappers. Once called, the classes are unmapped and can be later re-mapped with new mappers.
clear_mappers()is not for normal use, as there is literally no valid usage for it outside of very specific testing scenarios. Normally, mappers are permanent structural components of user-defined classes, and are never discarded independently of their class. If a mapped class itself is garbage collected, its mapper is automatically disposed of as well. As such,clear_mappers()is only for usage in test suites that re-use the same classes with different mappings, which is itself an extremely rare use case - the only such use case is in fact SQLAlchemy’s own test suite, and possibly the test suites of other ORM extension libraries which intend to test various combinations of mapper construction upon a fixed set of classes.
- function sqlalchemy.orm.util.identity_key(*args, **kwargs)¶
- Generate “identity key” tuples, as are used as keys in the
Session.identity_mapdictionary.This function has several call styles:
identity_key(class, ident, identity_token=token)This form receives a mapped class and a primary key scalar or tuple 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. The instance need not be persistent, only that its primary key attributes are populated (else the key will contain
Nonefor those missing values).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 though
Mapper.identity_key_from_instance(), which will have the effect of performing a database check for the corresponding row if 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 a database result row as a
RowProxyobject.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:
RowProxyrow returned by aResultProxy(must be given as a keyword arg)- param identity_token:
optional identity token
New in version 1.2: added identity_token
- function sqlalchemy.orm.polymorphic_union(table_map, typecolname, aliasname='p_union', cast_nulls=True)¶
Create a
UNIONstatement used by a polymorphic mapper.See Concrete Table Inheritance for an example of how this is used.
- Parameters:
table_map – mapping of polymorphic identities to
Tableobjects.typecolname – string name of a “discriminator” column, which will be derived from the query, producing the polymorphic identity for each row. If
None, no polymorphic discriminator is generated.aliasname – name of the
alias()construct generated.cast_nulls – if True, non-existent columns, which are represented as labeled NULLs, will be passed into CAST. This is a legacy behavior that is problematic on some backends such as Oracle - in which case it can be set to False.
- class 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, _polymorphic_map=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, _compiled_cache_size=100)¶
Define the correlation of class attributes to database table columns.
The
Mapperobject is instantiated using themapper()function. For information about instantiating newMapperobjects, see that function’s documentation.When
mapper()is used explicitly to link a user defined class with table metadata, this is referred to as classical mapping. Modern SQLAlchemy usage tends to favor thesqlalchemy.ext.declarativeextension for class configuration, which makes usage ofmapper()behind the scenes.Given a particular class known to be mapped by the ORM, the
Mapperwhich maintains it can be acquired using theinspect()function:from sqlalchemy import inspect mapper = inspect(MyClass)
A class which was mapped by the
sqlalchemy.ext.declarativeextension will also have its mapper available via the__mapper__attribute.Members
__init__(), add_properties(), add_property(), all_orm_descriptors, attrs, base_mapper, c, cascade_iterator(), class_, class_manager, column_attrs, columns, common_parent(), composites, concrete, configured, entity, get_property(), get_property_by_column(), identity_key_from_instance(), identity_key_from_primary_key(), identity_key_from_row(), inherits, is_mapper, isa(), iterate_properties, local_table, mapped_table, mapper, non_primary, persist_selectable, polymorphic_identity, polymorphic_iterator(), polymorphic_map, polymorphic_on, primary_key, primary_key_from_instance(), primary_mapper(), relationships, selectable, self_and_descendants, single, synonyms, tables, validators, with_polymorphic_mappers
Class signature
class
sqlalchemy.orm.Mapper(sqlalchemy.orm.base.InspectionAttr)-
method
sqlalchemy.orm.Mapper.__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, _polymorphic_map=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, _compiled_cache_size=100)¶ Construct a new
Mapperobject.This constructor is mirrored as a public API function; see
sqlalchemy.orm.mapper()for a full usage and argument description.
-
method
sqlalchemy.orm.Mapper.add_properties(dict_of_properties)¶ Add the given dictionary of properties to this mapper, using add_property.
-
method
sqlalchemy.orm.Mapper.add_property(key, prop)¶ Add an individual MapperProperty to this mapper.
If the mapper has not been configured yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been configured, then the given MapperProperty is configured immediately.
-
attribute
sqlalchemy.orm.Mapper.all_orm_descriptors¶ A namespace of all
InspectionAttrattributes associated with the mapped class.These attributes are in all cases Python descriptors associated with the mapped class or its superclasses.
This namespace includes attributes that are mapped to the class as well as attributes declared by extension modules. It includes any Python descriptor type that inherits from
InspectionAttr. This includesQueryableAttribute, as well as extension types such ashybrid_property,hybrid_methodandAssociationProxy.To distinguish between mapped attributes and extension attributes, the attribute
InspectionAttr.extension_typewill refer to a constant that distinguishes between different extension types.The sorting of the attributes is based on the following rules:
Iterate through the class and its superclasses in order from subclass to superclass (i.e. iterate through
cls.__mro__)For each class, yield the attributes in the order in which they appear in
__dict__, with the exception of those in step 3 below. In Python 3.6 and above this ordering will be the same as that of the class’ construction, with the exception of attributes that were added after the fact by the application or the mapper.If a certain attribute key is also in the superclass
__dict__, then it’s included in the iteration for that class, and not the class in which it first appeared.
The above process produces an ordering that is deterministic in terms of the order in which attributes were assigned to the class.
Changed in version 1.3.19: ensured deterministic ordering for
Mapper.all_orm_descriptors().When dealing with a
QueryableAttribute, theQueryableAttribute.propertyattribute refers to theMapperPropertyproperty, which is what you get when referring to the collection of mapped properties viaMapper.attrs.Warning
The
Mapper.all_orm_descriptorsaccessor namespace is an instance ofOrderedProperties. This is a dictionary-like object which includes a small number of named methods such asOrderedProperties.items()andOrderedProperties.values(). When accessing attributes dynamically, favor using the dict-access scheme, e.g.mapper.all_orm_descriptors[somename]overgetattr(mapper.all_orm_descriptors, somename)to avoid name collisions.See also
-
attribute
sqlalchemy.orm.Mapper.attrs¶ A namespace of all
MapperPropertyobjects associated this mapper.This is an object that provides each property based on its key name. For instance, the mapper for a
Userclass which hasUser.nameattribute would providemapper.attrs.name, which would be theColumnPropertyrepresenting thenamecolumn. The namespace object can also be iterated, which would yield eachMapperProperty.Mapperhas several pre-filtered views of this attribute which limit the types of properties returned, includingsynonyms,column_attrs,relationships, andcomposites.Warning
The
Mapper.attrsaccessor namespace is an instance ofOrderedProperties. This is a dictionary-like object which includes a small number of named methods such asOrderedProperties.items()andOrderedProperties.values(). When accessing attributes dynamically, favor using the dict-access scheme, e.g.mapper.attrs[somename]overgetattr(mapper.attrs, somename)to avoid name collisions.See also
-
attribute
sqlalchemy.orm.Mapper.base_mapper = None¶ The base-most
Mapperin an inheritance chain.In a non-inheriting scenario, this attribute will always be this
Mapper. In an inheritance scenario, it references theMapperwhich is parent to all otherMapperobjects in the inheritance chain.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.c = None¶ A synonym for
Mapper.columns.
-
method
sqlalchemy.orm.Mapper.cascade_iterator(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 generic object 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 per the 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 to traverse all objects without relying on cascades.
-
attribute
sqlalchemy.orm.Mapper.class_ = None¶ The Python class which this
Mappermaps.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.class_manager = None¶ The
ClassManagerwhich maintains event listeners and class-bound descriptors for thisMapper.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.column_attrs¶ Return a namespace of all
ColumnPropertyproperties maintained by thisMapper.See also
Mapper.attrs- namespace of allMapperPropertyobjects.
-
attribute
sqlalchemy.orm.Mapper.columns = None¶ A collection of
Columnor other scalar expression objects maintained by thisMapper.The collection behaves the same as that of the
cattribute on anyTableobject, except that only those columns included in this mapping are present, and are keyed based on the attribute name defined in the mapping, not necessarily thekeyattribute of theColumnitself. Additionally, scalar expressions mapped bycolumn_property()are also present here.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
method
sqlalchemy.orm.Mapper.common_parent(other)¶ Return true if the given mapper shares a common inherited parent as this mapper.
-
attribute
sqlalchemy.orm.Mapper.composites¶ Return a namespace of all
CompositePropertyproperties maintained by thisMapper.See also
Mapper.attrs- namespace of allMapperPropertyobjects.
-
attribute
sqlalchemy.orm.Mapper.concrete = None¶ Represent
Trueif thisMapperis a concrete inheritance mapper.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.configured = None¶ Represent
Trueif thisMapperhas been configured.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
See also
-
attribute
sqlalchemy.orm.Mapper.entity¶ Part of the inspection API.
Returns self.class_.
-
method
sqlalchemy.orm.Mapper.get_property(key, _configure_mappers=True)¶ return a MapperProperty associated with the given key.
-
method
sqlalchemy.orm.Mapper.get_property_by_column(column)¶ Given a
Columnobject, return theMapperPropertywhich maps this column.
-
method
sqlalchemy.orm.Mapper.identity_key_from_instance(instance)¶ Return the identity key for the given instance, based on its primary key attributes.
If the instance’s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists,
ObjectDeletedErroris raised.This value is typically also found on the instance state under the attribute name key.
-
method
sqlalchemy.orm.Mapper.identity_key_from_primary_key(primary_key, identity_token=None)¶ Return an identity-map key for use in storing/retrieving an item from an identity map.
- Parameters:
primary_key – A list of values indicating the identifier.
-
method
sqlalchemy.orm.Mapper.identity_key_from_row(row, identity_token=None, adapter=None)¶ Return an identity-map key for use in storing/retrieving an item from the identity map.
-
attribute
sqlalchemy.orm.Mapper.inherits = None¶ References the
Mapperwhich thisMapperinherits from, if any.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.is_mapper = True¶ Part of the inspection API.
-
method
sqlalchemy.orm.Mapper.isa(other)¶ Return True if the this mapper inherits from the given mapper.
-
attribute
sqlalchemy.orm.Mapper.iterate_properties¶ return an iterator of all MapperProperty objects.
-
attribute
sqlalchemy.orm.Mapper.local_table = None¶ The
Selectablewhich thisMappermanages.Typically is an instance of
TableorAlias. May also beNone.The “local” table is the selectable that the
Mapperis directly responsible for managing from an attribute access and flush perspective. For non-inheriting mappers, the local table is the same as the “mapped” table. For joined-table inheritance mappers, local_table will be the particular sub-table of the overall “join” which thisMapperrepresents. If this mapper is a single-table inheriting mapper, local_table will beNone.See also
-
attribute
sqlalchemy.orm.Mapper.mapped_table¶ Deprecated since version 1.3: Use .persist_selectable
-
attribute
sqlalchemy.orm.Mapper.mapper¶ Part of the inspection API.
Returns self.
-
attribute
sqlalchemy.orm.Mapper.non_primary = None¶ Represent
Trueif thisMapperis a “non-primary” mapper, e.g. a mapper that is used only to select rows but not for persistence management.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.persist_selectable = None¶ The
Selectableto which thisMapperis mapped.Typically an instance of
Table,Join, orAlias.The
Mapper.persist_selectableis separate fromMapper.selectablein that the former represents columns that are mapped on this class or its superclasses, whereas the latter may be a “polymorphic” selectable that contains additional columns which 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_selectableis also separate fromMapper.local_table, which represents the set of columns that are locally mapped on this class directly.
-
attribute
sqlalchemy.orm.Mapper.polymorphic_identity = None¶ Represent an identifier which is matched against the
Mapper.polymorphic_oncolumn during result row loading.Used only with inheritance, this object can be of any type which is comparable to the type of column represented by
Mapper.polymorphic_on.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
method
sqlalchemy.orm.Mapper.polymorphic_iterator()¶ Iterate through the collection including this mapper and all descendant mappers.
This includes not just the immediately inheriting mappers but all their inheriting mappers as well.
To iterate through an entire hierarchy, use
mapper.base_mapper.polymorphic_iterator().
-
attribute
sqlalchemy.orm.Mapper.polymorphic_map = None¶ A mapping of “polymorphic identity” identifiers mapped to
Mapperinstances, within an inheritance scenario.The identifiers can be of any type which is comparable to the type of column represented by
Mapper.polymorphic_on.An inheritance chain of mappers will all reference the same polymorphic map object. The object is used to correlate incoming result rows to target mappers.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.polymorphic_on = None¶ The
Columnor SQL expression specified as thepolymorphic_onargument for thisMapper, within an inheritance scenario.This attribute is normally a
Columninstance but may 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.
-
attribute
sqlalchemy.orm.Mapper.primary_key = None¶ An iterable containing the collection of
Columnobjects which comprise the ‘primary key’ of the mapped table, from the perspective of thisMapper.This list is against the selectable in
Mapper.persist_selectable. In the case of inheriting mappers, some columns may be managed by a superclass mapper. For example, in the case of aJoin, the primary key is determined by all of the primary key columns across all tables referenced by theJoin.The list is also not necessarily the same as the primary key column collection associated with the underlying tables; the
Mapperfeatures aprimary_keyargument that can override what theMapperconsiders as primary key columns.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
method
sqlalchemy.orm.Mapper.primary_key_from_instance(instance)¶ Return the list of primary key values for the given instance.
If the instance’s state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists,
ObjectDeletedErroris raised.
-
method
sqlalchemy.orm.Mapper.primary_mapper()¶ Return the primary mapper corresponding to this mapper’s class key (class).
-
attribute
sqlalchemy.orm.Mapper.relationships¶ A namespace of all
RelationshipPropertyproperties maintained by thisMapper.Warning
the
Mapper.relationshipsaccessor namespace is an instance ofOrderedProperties. This is a dictionary-like object which includes a small number of named methods such asOrderedProperties.items()andOrderedProperties.values(). When accessing attributes dynamically, favor using the dict-access scheme, e.g.mapper.relationships[somename]overgetattr(mapper.relationships, somename)to avoid name collisions.See also
Mapper.attrs- namespace of allMapperPropertyobjects.
-
attribute
sqlalchemy.orm.Mapper.selectable¶ The
select()construct thisMapperselects from by default.Normally, this is equivalent to
persist_selectable, unless thewith_polymorphicfeature is in use, in which case the full “polymorphic” selectable is returned.
-
attribute
sqlalchemy.orm.Mapper.self_and_descendants¶ The collection including this mapper and all descendant mappers.
This includes not just the immediately inheriting mappers but all their inheriting mappers as well.
-
attribute
sqlalchemy.orm.Mapper.single = None¶ Represent
Trueif thisMapperis a single table inheritance mapper.Mapper.local_tablewill beNoneif this flag is set.This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
-
attribute
sqlalchemy.orm.Mapper.synonyms¶ Return a namespace of all
SynonymPropertyproperties maintained by thisMapper.See also
Mapper.attrs- namespace of allMapperPropertyobjects.
-
attribute
sqlalchemy.orm.Mapper.tables = None¶ An iterable containing the collection of
Tableobjects which thisMapperis aware of.If the mapper is mapped to a
Join, or anAliasrepresenting aSelect, the individualTableobjects 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.
-
attribute
sqlalchemy.orm.Mapper.validators = None¶ An immutable dictionary of attributes which have been decorated using the
validates()decorator.The dictionary contains string attribute names as keys mapped to the actual validation method.
-
attribute
sqlalchemy.orm.Mapper.with_polymorphic_mappers¶ The list of
Mapperobjects included in the default “polymorphic” query.
-
method