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 Mapper
object.
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, including class_
,
local_table
, properties
, and inherits
.
Other options are passed to mapper()
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: |
|
---|
sqlalchemy.orm.
object_mapper
(instance)¶Given an object, return the primary Mapper associated with the object instance.
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 raise
sqlalchemy.exc.NoInspectionAvailable
if the instance is
not part of a mapping.
sqlalchemy.orm.
class_mapper
(class_, configure=True)¶Given a class, return the primary Mapper
associated
with the key.
Raises UnmappedClassError
if no mapping is configured
on the given class, or ArgumentError
if 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.NoInspectionAvailable
if the class is not mapped.
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 before
configure_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 individual
Mapper
is 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 after
configure_mappers()
is complete; at this stage, all
Mapper
objects 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.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.
sqlalchemy.orm.util.
identity_key
(*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 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 None
for 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 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: |
|
param identity_token: | |
optional identity token New in version 1.2: added identity_token |
sqlalchemy.orm.util.
polymorphic_union
(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 how this is used.
Parameters: |
|
---|
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, _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)¶Bases: sqlalchemy.orm.base.InspectionAttr
Define the correlation of class attributes to database table columns.
The Mapper
object is instantiated using the
mapper()
function. For information
about instantiating new Mapper
objects, 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 the
sqlalchemy.ext.declarative
extension for class
configuration, which
makes usage of mapper()
behind the scenes.
Given a particular class known to be mapped by the ORM,
the Mapper
which maintains it can be acquired
using 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, _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 Mapper
object.
This constructor is mirrored as a public API function; see mapper()
for a full usage and argument description.
add_properties
(dict_of_properties)¶Add the given dictionary of properties to this mapper, using add_property.
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.
all_orm_descriptors
¶A namespace of all InspectionAttr
attributes 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 includes
QueryableAttribute
, as well as extension types such as
hybrid_property
, hybrid_method
and
AssociationProxy
.
To distinguish between mapped attributes and extension attributes,
the attribute InspectionAttr.extension_type
will refer
to a constant that distinguishes between different extension types.
When dealing with a QueryableAttribute
, the
QueryableAttribute.property
attribute refers to the
MapperProperty
property, which is what you get when
referring to the collection of mapped properties via
Mapper.attrs
.
Warning
The Mapper.all_orm_descriptors
accessor namespace is an
instance of OrderedProperties
. This is
a dictionary-like object which includes a small number of
named methods such as OrderedProperties.items()
and OrderedProperties.values()
. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. mapper.all_orm_descriptors[somename]
over
getattr(mapper.all_orm_descriptors, somename)
to avoid name
collisions.
See also
attrs
¶A namespace of all MapperProperty
objects
associated this mapper.
This is an object that provides each property based on
its key name. For instance, the mapper for a
User
class which has User.name
attribute would
provide mapper.attrs.name
, which would be the
ColumnProperty
representing the name
column. The namespace object can also be iterated,
which would yield each MapperProperty
.
Mapper
has several pre-filtered views
of this attribute which limit the types of properties
returned, including synonyms
, column_attrs
,
relationships
, and composites
.
Warning
The Mapper.attrs
accessor namespace is an
instance of OrderedProperties
. This is
a dictionary-like object which includes a small number of
named methods such as OrderedProperties.items()
and OrderedProperties.values()
. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. mapper.attrs[somename]
over
getattr(mapper.attrs, somename)
to avoid name collisions.
See also
base_mapper
= None¶The base-most Mapper
in an inheritance chain.
In a non-inheriting scenario, this attribute will always be this
Mapper
. In an inheritance scenario, it references
the 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.
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: |
|
---|---|
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.
class_
= None¶The Python class which this Mapper
maps.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
class_manager
= None¶The ClassManager
which maintains event listeners
and class-bound descriptors for this Mapper
.
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 this Mapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
columns
= None¶A collection of Column
or other scalar expression
objects maintained by this Mapper
.
The collection behaves the same as that of the c
attribute on
any Table
object, 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 the key
attribute of the
Column
itself. Additionally, scalar expressions mapped
by column_property()
are also present here.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
common_parent
(other)¶Return true if the given mapper shares a common inherited parent as this mapper.
composites
¶Return a namespace of all CompositeProperty
properties maintained by this Mapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
concrete
= None¶Represent True
if this Mapper
is a concrete
inheritance 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
entity
¶Part of the inspection API.
Returns self.class_.
get_property
(key, _configure_mappers=True)¶return a MapperProperty associated with the given key.
get_property_by_column
(column)¶Given a Column
object, return the
MapperProperty
which maps this column.
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,
ObjectDeletedError
is raised.
This value is typically also found on the instance state under the attribute name key.
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. |
---|
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.
Parameters: | row¶ – A RowProxy instance. The columns which are
mapped by this Mapper should be locatable in the row,
preferably via the Column object directly (as is the case
when a select() construct is executed), or via string names of
the form <tablename>_<colname> . |
---|
inherits
= None¶References the Mapper
which this Mapper
inherits from, if any.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
is_mapper
= True¶Part of the inspection API.
isa
(other)¶Return True if the this mapper inherits from the given mapper.
iterate_properties
¶return an iterator of all MapperProperty objects.
local_table
= None¶The Selectable
which this Mapper
manages.
Typically is an instance of Table
or Alias
.
May also be None
.
The “local” table is the
selectable that the Mapper
is 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
this Mapper
represents. If this mapper is a
single-table inheriting mapper, local_table will be None
.
See also
mapped_table
¶Deprecated since version 1.3: Use .persist_selectable
mapper
¶Part of the inspection API.
Returns self.
non_primary
= None¶Represent True
if this Mapper
is 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.
persist_selectable
= None¶The Selectable
to which this Mapper
is mapped.
Typically an instance of Table
, Join
, or
Alias
.
The Mapper.persist_selectable
is separate from
Mapper.selectable
in 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_selectable
is also separate from
Mapper.local_table
, which represents the set of columns that
are locally mapped on this class directly.
polymorphic_identity
= 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 is
comparable to the type of column represented by
polymorphic_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 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()
.
polymorphic_map
= 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 the
type of column represented by 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.
polymorphic_on
= None¶The Column
or SQL expression specified as the
polymorphic_on
argument
for this Mapper
, within an inheritance scenario.
This attribute is normally a Column
instance but
may also be an expression, such as one derived from
cast()
.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
primary_key
= None¶An iterable containing the collection of Column
objects
which comprise the ‘primary key’ of the mapped table, from the
perspective of this Mapper
.
This list is against the selectable in persist_selectable
.
In the case of inheriting mappers, some columns may be managed by a
superclass mapper. For example, in the case of a Join
, the
primary key is determined by all of the primary key columns across all
tables referenced by the Join
.
The list is also not necessarily the same as the primary key column
collection associated with the underlying tables; the Mapper
features a primary_key
argument that can override what the
Mapper
considers as primary key columns.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
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,
ObjectDeletedError
is raised.
primary_mapper
()¶Return the primary mapper corresponding to this mapper’s class key (class).
relationships
¶A namespace of all RelationshipProperty
properties
maintained by this Mapper
.
Warning
the Mapper.relationships
accessor namespace is an
instance of OrderedProperties
. This is
a dictionary-like object which includes a small number of
named methods such as OrderedProperties.items()
and OrderedProperties.values()
. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. mapper.relationships[somename]
over
getattr(mapper.relationships, somename)
to avoid name
collisions.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
selectable
¶The select()
construct this Mapper
selects from
by default.
Normally, this is equivalent to persist_selectable
, unless
the with_polymorphic
feature is in use, in which case the
full “polymorphic” selectable is returned.
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.
single
= None¶Represent True
if this Mapper
is a single table
inheritance 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 this Mapper
.
See also
Mapper.attrs
- namespace of all MapperProperty
objects.
tables
= None¶An iterable containing the collection of Table
objects
which this Mapper
is aware of.
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 decorated
using the validates()
decorator.
The dictionary contains string attribute names as keys mapped to the actual validation method.