Class Mapping API

    class sqlalchemy.orm.``registry(metadata=None, class_registry=None, constructor=<function _declarative_constructor>, _bind=None)

    Generalized registry for mapping classes.

    The registry serves as the basis for maintaining a collection of mappings, and provides configurational hooks used to map classes.

    The three general kinds of mappings supported are Declarative Base, Declarative Decorator, and Imperative Mapping. All of these mapping styles may be used interchangeably:

    • returns a new declarative base class, and is the underlying implementation of the declarative_base() function.

    • provides a class decorator that will apply declarative mapping to a class without the use of a declarative base class.

    • registry.map_imperatively() will produce a for a class without scanning the class for declarative class attributes. This method suits the use case historically provided by the mapper() classical mapping function.

    New in version 1.4.

    See also

    - overview of class mapping styles.

    • method sqlalchemy.orm.registry.__init__(metadata=None, class_registry=None, constructor=<function _declarative_constructor>, _bind=None)

      Construct a new

      • Parameters

        • metadata – An optional MetaData instance. All objects generated using declarative table mapping will make use of this MetaData collection. If this argument is left at its default of None, a blank collection is created.

        • constructor – Specify the implementation for the __init__ function on a mapped class that has no __init__ of its own. Defaults to an implementation that assigns **kwargs for declared fields and relationships to an instance. If None is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics.

        • class_registry – optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of relationship() and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships.

    • method as_declarative_base(\*kw*)

      Class decorator which will invoke registry.generate_base() for a given base class.

      E.g.:

      All keyword arguments passed to are passed along to registry.generate_base().

    • method configure(cascade=False)

      Configure all as-yet unconfigured mappers in this registry.

      The configure step is used to reconcile and initialize the linkages between mapped classes, as well as to invoke configuration events such as the MapperEvents.before_configured() and , which may be used by ORM extensions or user-defined extension hooks.

      If one or more mappers in this registry contain relationship() constructs that refer to mapped classes in other registries, this registry is said to be dependent on those registries. In order to configure those dependent registries automatically, the flag should be set to True. Otherwise, if they are not configured, an exception will be raised. The rationale behind this behavior is to allow an application to programmatically invoke configuration of registries while controlling whether or not the process implicitly reaches other registries.

      As an alternative to invoking registry.configure(), the ORM function function may be used to ensure configuration is complete for all registry objects in memory. This is generally simpler to use and also predates the usage of objects overall. However, this function will impact all mappings throughout the running Python process and may be more memory/time consuming for an application that has many registries in use for different purposes that may not be needed immediately.

      See also

      configure_mappers()

      New in version 1.4.0b2.

    • method dispose(cascade=False)

      Dispose of all mappers in this registry.

      After invocation, all the classes that were mapped within this registry will no longer have class instrumentation associated with them. This method is the per- analogue to the application-wide clear_mappers() function.

      If this registry contains mappers that are dependencies of other registries, typically via links, then those registries must be disposed as well. When such registries exist in relation to this one, their registry.dispose() method will also be called, if the flag is set to True; otherwise, an error is raised if those registries were not already disposed.

      New in version 1.4.0b2.

      See also

      clear_mappers()

    • method generate_base(mapper=None, cls=<class ‘object’>, name=’Base’, metaclass=<class ‘sqlalchemy.orm.decl_api.DeclarativeMeta’>)

      Generate a declarative base class.

      Classes that inherit from the returned class object will be automatically mapped using declarative mapping.

      E.g.:

      1. from sqlalchemy.orm import registry
      2. mapper_registry = registry()
      3. Base = mapper_registry.generate_base()
      4. class MyClass(Base):
      5. __tablename__ = "my_table"
      6. id = Column(Integer, primary_key=True)

      The above dynamically generated class is equivalent to the non-dynamic example below:

      1. from sqlalchemy.orm import registry
      2. from sqlalchemy.orm.decl_api import DeclarativeMeta
      3. mapper_registry = registry()
      4. class Base(metaclass=DeclarativeMeta):
      5. __abstract__ = True
      6. registry = mapper_registry
      7. metadata = mapper_registry.metadata

      The registry.generate_base() method provides the implementation for the function, which creates the registry and base class all at once.

      See the section for background and examples.

      • Parameters

        • mapper – An optional callable, defaults to mapper(). This function is used to generate new objects.

        • cls – Defaults to object. A type to use as the base for the generated declarative base class. May be a class or tuple of classes.

        • name – Defaults to Base. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging.

        • metaclass – Defaults to DeclarativeMeta. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class.

    1. See also
    2. [Declarative Mapping]($e8d4cf43cc9f8217.md#orm-declarative-mapping)
    3. [`declarative_base()`](#sqlalchemy.orm.declarative_base "sqlalchemy.orm.declarative_base")
    • method sqlalchemy.orm.registry.map_declaratively(cls)

      Map a class declaratively.

      In this form of mapping, the class is scanned for mapping information, including for columns to be associated with a table, and/or an actual table object.

      Returns the object.

      E.g.:

      1. from sqlalchemy.orm import registry
      2. mapper_registry = registry()
      3. class Foo:
      4. __tablename__ = 'some_table'
      5. id = Column(Integer, primary_key=True)
      6. name = Column(String)
      7. mapper = mapper_registry.map_declaratively(Foo)

      This function is more conveniently invoked indirectly via either the registry.mapped() class decorator or by subclassing a declarative metaclass generated from .

      See the section Declarative Mapping for complete details and examples.

      • Parameters

        cls – class to be mapped.

        Returns

        a object.

      See also

      Declarative Mapping

      - more common decorator interface to this function.

      registry.map_imperatively()

    • method map_imperatively(class_, local_table=None, \*kw*)

      Map a class imperatively.

      In this form of mapping, the class is not scanned for any mapping information. Instead, all mapping constructs are passed as arguments.

      This method is intended to be fully equivalent to the classic SQLAlchemy mapper() function, except that it’s in terms of a particular registry.

      E.g.:

      1. from sqlalchemy.orm import registry
      2. mapper_registry = registry()
      3. my_table = Table(
      4. "my_table",
      5. mapper_registry.metadata,
      6. Column('id', Integer, primary_key=True)
      7. )
      8. class MyClass:
      9. pass
      10. mapper_registry.map_imperatively(MyClass, my_table)

      See the section for complete background and usage examples.

      • Parameters

        • class_ – The class to be mapped. Corresponds to the mapper.class_ parameter.

        • local_table – the or other FromClause object that is the subject of the mapping. Corresponds to the parameter.

        • **kw – all other keyword arguments are passed to the mapper() function directly.

    1. See also
    2. [Imperative (a.k.a. Classical) Mappings]($e8d4cf43cc9f8217.md#orm-imperative-mapping)
    3. [Declarative Mapping]($e8d4cf43cc9f8217.md#orm-declarative-mapping)
    • method mapped(cls)

      Class decorator that will apply the Declarative mapping process to a given class.

      E.g.:

      1. from sqlalchemy.orm import registry
      2. mapper_registry = registry()
      3. @mapper_registry.mapped
      4. class Foo:
      5. __tablename__ = 'some_table'
      6. id = Column(Integer, primary_key=True)
      7. name = Column(String)

      See the section Declarative Mapping for complete details and examples.

      • Parameters

        cls – class to be mapped.

        Returns

        the class that was passed.

      See also

      registry.generate_base() - generates a base class that will apply Declarative mapping to subclasses automatically using a Python metaclass.

    • attribute mappers

      read only collection of all Mapper objects.

    function sqlalchemy.orm.``declarative_base(bind=None, metadata=None, mapper=None, cls=<class ‘object’>, name=’Base’, constructor=<function _declarative_constructor>, class_registry=None, metaclass=<class ‘sqlalchemy.orm.decl_api.DeclarativeMeta’>)

    Construct a base class for declarative class definitions.

    The new base class will be given a metaclass that produces appropriate objects and makes the appropriate mapper() calls based on the information provided declaratively in the class and any subclasses of the class.

    The function is a shorthand version of using the registry.generate_base() method. That is, the following:

    Is equivalent to:

    1. from sqlalchemy.orm import registry
    2. mapper_registry = registry()
    3. Base = mapper_registry.generate_base()

    See the docstring for and registry.generate_base() for more details.

    Changed in version 1.4: The function is now a specialization of the more generic registry class. The function also moves to the sqlalchemy.orm package from the declarative.ext package.

    • Parameters

      • bind

        An optional Connectable, will be assigned the bind attribute on the instance.

        Deprecated since version 1.4: The “bind” argument to declarative_base is deprecated and will be removed in SQLAlchemy 2.0.

      • metadata – An optional MetaData instance. All objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The MetaData instance will be available via the metadata attribute of the generated declarative base class.

      • mapper – An optional callable, defaults to . Will be used to map subclasses to their Tables.

      • cls – Defaults to object. A type to use as the base for the generated declarative base class. May be a class or tuple of classes.

      • name – Defaults to Base. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging.

      • constructor – Specify the implementation for the __init__ function on a mapped class that has no __init__ of its own. Defaults to an implementation that assigns **kwargs for declared fields and relationships to an instance. If None is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics.

      • class_registry – optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of relationship() and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships.

      • metaclass – Defaults to DeclarativeMeta. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class.

    See also

    function sqlalchemy.orm.``as_declarative(\*kw*)

    Class decorator which will adapt a given class into a declarative_base().

    This function makes use of the method, by first creating a registry automatically and then invoking the decorator.

    E.g.:

    1. @as_declarative()
    2. class Base(object):
    3. @declared_attr
    4. def __tablename__(cls):
    5. return cls.__name__.lower()
    6. id = Column(Integer, primary_key=True)
    7. class MyMappedClass(Base):
    8. # ...

    See also

    class sqlalchemy.orm.``declared_attr(fget, cascading=False)

    Mark a class-level method as representing the definition of a mapped property or special declarative member name.

    @declared_attr turns the attribute into a scalar-like property that can be invoked from the uninstantiated class. Declarative treats attributes specifically marked with @declared_attr as returning a construct that is specific to mapping or declarative table configuration. The name of the attribute is that of what the non-dynamic version of the attribute would be.

    @declared_attr is more often than not applicable to mixins, to define relationships that are to be applied to different implementors of the class:

    1. class ProvidesUser(object):
    2. "A mixin that adds a 'user' relationship to classes."
    3. @declared_attr
    4. def user(self):
    5. return relationship("User")

    It also can be applied to mapped classes, such as to provide a “polymorphic” scheme for inheritance:

    1. class Employee(Base):
    2. id = Column(Integer, primary_key=True)
    3. type = Column(String(50), nullable=False)
    4. @declared_attr
    5. def __tablename__(cls):
    6. return cls.__name__.lower()
    7. @declared_attr
    8. def __mapper_args__(cls):
    9. if cls.__name__ == 'Employee':
    10. return {
    11. "polymorphic_on":cls.type,
    12. "polymorphic_identity":"Employee"
    13. }
    14. else:
    15. return {"polymorphic_identity":cls.__name__}

    Class signature

    class sqlalchemy.orm.declared_attr (sqlalchemy.orm.base._MappedAttribute, builtins.property)

    • attribute cascading

      Mark a declared_attr as cascading.

      This is a special-use modifier which indicates that a column or MapperProperty-based declared attribute should be configured distinctly per mapped subclass, within a mapped-inheritance scenario.

      Warning

      The modifier has several limitations:

      • The flag only applies to the use of declared_attr on declarative mixin classes and classes; it currently has no effect when used on a mapped class directly.

      • The flag only applies to normally-named attributes, e.g. not any special underscore attributes such as __tablename__. On these attributes it has no effect.

      • The flag currently does not allow further overrides down the class hierarchy; if a subclass tries to override the attribute, a warning is emitted and the overridden attribute is skipped. This is a limitation that it is hoped will be resolved at some point.

      Below, both MyClass as well as MySubClass will have a distinct id Column object established:

      1. class HasIdMixin(object):
      2. @declared_attr.cascading
      3. def id(cls):
      4. if has_inherited_table(cls):
      5. return Column(
      6. ForeignKey('myclass.id'), primary_key=True
      7. )
      8. else:
      9. return Column(Integer, primary_key=True)
      10. class MyClass(HasIdMixin, Base):
      11. __tablename__ = 'myclass'
      12. # ...
      13. class MySubClass(MyClass):
      14. ""
      15. # ...

      The behavior of the above configuration is that MySubClass will refer to both its own id column as well as that of MyClass underneath the attribute named some_id.

      See also

      Mixing in Columns in Inheritance Scenarios

    function sqlalchemy.orm.``has_inherited_table(cls)

    Given a class, return True if any of the classes it inherits from has a mapped table, otherwise return False.

    This is used in declarative mixins to build attributes that behave differently for the base class vs. a subclass in an inheritance hierarchy.

    See also

    function sqlalchemy.orm.``synonym_for(name, map_column=False)

    Decorator that produces an synonym() attribute in conjunction with a Python descriptor.

    The function being decorated is passed to as the synonym.descriptor parameter:

    1. class MyClass(Base):
    2. __tablename__ = 'my_table'
    3. id = Column(Integer, primary_key=True)
    4. _job_status = Column("job_status", String(50))
    5. @synonym_for("job_status")
    6. @property
    7. def job_status(self):
    8. return "Status: %s" % self._job_status

    The feature of SQLAlchemy is typically preferred instead of synonyms, which is a more legacy feature.

    See also

    Synonyms - Overview of synonyms

    - the mapper-level function

    Using Descriptors and Hybrids - The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than can be achieved with synonyms.

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

    Direct constructor for a new object.

    The mapper() function is normally invoked through the use of the object through either the Declarative or mapping styles.

    Changed in version 1.4: The mapper() function should not be called directly for classical mapping; for a classical mapping configuration, use the method. The mapper() function may become private in a future release.

    Parameters documented below may be passed to either the method, or may be passed in the __mapper_args__ declarative class attribute described at Mapper Configuration Options with Declarative.

      • class_ – The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself.

      • local_table – The or other selectable to which the class is mapped. May be None if 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 the Table produced as a result of the __tablename__ and arguments 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 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 a MapperEvents listener requires being called in between individual row persistence operations.

      • column_prefix

        A string which will be prepended to the mapped attribute name when objects 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 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_rows as 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 SELECT statement per row inserted or updated, which note can add significant performance overhead. However, if the target database supports , 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

        Fetching Server-Generated Defaults

        Changed in version 0.9.0: The eager_defaults option can now make use of 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.

      • include_properties

        An inclusive list or set of string column names to map.

        See for an example.

      • inherits

        A mapped class or the corresponding Mapper of one indicating a superclass to which this should 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.

        See also

        Mapping Class Inheritance Hierarchies

      • 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_condition is used and the columns present are missing a configuration, this parameter can be used to specify which columns are “foreign”. In most cases can be left as None.

      • legacy_is_orphan

        Boolean, defaults to False. When True, 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 owning Session only when it is de-associated from all parents that specify a delete-orphan cascade 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 specify delete-orphan cascade. 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 for more detail on this change.

      • non_primary

      • Specify that this Mapper

        is in addition to the “primary” mapper, that is, the one used for persistence. The created 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_primary parameter is deprecated, and will be removed in a future release. The functionality of non primary mappers is now better suited using the construct, which can also be used as the target of a relationship() in 1.3.

      See also

      - the new pattern that removes the need for the Mapper.non_primary flag.

      • passive_deletes

        Indicates DELETE behavior of foreign key columns when a joined-table inheritance entity is being deleted. Defaults to False for a base mapper; for an inheriting mapper, defaults to False unless the value is set to True on the superclass mapper.

        When True, it is assumed that ON DELETE CASCADE is 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 True is 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

        - description of similar feature as used with relationship()

        - supporting ON UPDATE CASCADE for joined-table inheritance mappers

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

        mapper.passive_deletes - supporting ON DELETE CASCADE for joined-table inheritance mappers

      • polymorphic_load

      • Specifies “polymorphic loading” behavior

        for a subclass in an inheritance hierarchy (joined and single table inheritance only). Valid values are:

      New in version 1.2.

      See also

      Polymorphic Selectin Loading

      • 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 object that’s present in the mapped Table:

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

        It may also be specified as a SQL expression, as in this example where we use the construct to provide a conditional approach:

        It may also refer to any attribute configured with column_property(), or to the string name of one:

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

        When setting polymorphic_on to reference an attribute or expression that’s not present in the locally mapped , 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:

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

        Where above, we assign the value of polymorphic_identity for the mapped class to the discriminator attribute, thus persisting the value to the discriminator column 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.

        See also

        Mapping Class Inheritance Hierarchies

      • polymorphic_identity – Specifies the value which identifies this particular class as returned by the column expression referred to by the polymorphic_on setting. As rows are received, the value corresponding to the polymorphic_on column 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 instances, which define the persistence behavior of that attribute. Note that Column objects present in the mapped are automatically placed into ColumnProperty instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those MapperProperty instances declared in the declared class body.

      • primary_key – A list of objects which define the primary key to be used against this mapper’s selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.

      • version_id_col

        A Column that 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, a exception is thrown. By default, the column must be of Integer type, unless version_id_generator specifies an alternative version generator.

        See also

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

        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 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_generator supports server-side version number generation.

        See also

        Server Side Version Counters

      • 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

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

    This function is available via the inspection system as:

    1. inspect(instance).mapper

    Using the inspection system will raise if the instance is not part of a mapping.

    function sqlalchemy.orm.``class_mapper(class_, configure=True)

    Given a class, return the primary Mapper associated with the key.

    Raises if no mapping is configured on the given class, or ArgumentError if a non-class object is passed.

    Equivalent functionality is available via the function as:

    1. inspect(some_mapped_class)

    Using the inspection system will raise sqlalchemy.exc.NoInspectionAvailable if the class is not mapped.

    function sqlalchemy.orm.``configure_mappers()

    Initialize the inter-mapper relationships of all mappers that have been constructed thus far across all collections.

    The configure step is used to reconcile and initialize the relationship() linkages between mapped classes, as well as to invoke configuration events such as the and MapperEvents.after_configured(), which may be used by ORM extensions or user-defined extension hooks.

    Mapper configuration is normally invoked automatically, the first time mappings from a particular are used, as well as whenever mappings are used and additional not-yet-configured mappers have been constructed. The automatic configuration process however is local only to the registry involving the target mapper and any related objects which it may depend on; this is equivalent to invoking the registry.configure() method on a particular .

    By contrast, the configure_mappers() function will invoke the configuration process on all objects that exist in memory, and may be useful for scenarios where many individual registry objects that are nonetheless interrelated are in use.

    Changed in version 1.4: As of SQLAlchemy 1.4.0b2, this function works on a per- basis, locating all registry objects present and invoking the method on each. The registry.configure() method may be preferred to limit the configuration of mappers to those local to a particular and/or declarative base class.

    Points at which automatic configuration is invoked include when a mapped class is instantiated into an instance, as well as when ORM queries are emitted using Session.query() or with an ORM-enabled statement.

    The mapper configure process, whether invoked by configure_mappers() or from , provides several event hooks that can be used to augment the mapper configuration step. These hooks include:

    • MapperEvents.before_configured() - called once before or registry.configure() does any work; this can be used to establish additional options, properties, or related mappings before the operation proceeds.

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

    • - called once after configure_mappers() or is complete; at this stage, all Mapper objects that fall within the scope of the configuration operation 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, and may also have mappings that are still to be configured, if they are in other collections not part of the current scope of configuration.

    function sqlalchemy.orm.``clear_mappers()

    Remove all mappers from all classes.

    Changed in version 1.4: This function now locates all registry objects and calls upon the method of each.

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

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

      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 though , 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 Row object.

      E.g.:

    • param class

      mapped class (must be a positional argument)

      param row

      row returned by a CursorResult (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 UNION statement used by a polymorphic mapper.

    See for an example of how this is used.

    • Parameters

      • table_map – mapping of polymorphic identities to Table objects.

      • 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 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, 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 Mapper object is instantiated using the function. For information about instantiating new Mapper objects, see that function’s documentation.

    When 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 behind the scenes.

    Given a particular class known to be mapped by the ORM, the Mapper which maintains it can be acquired using the function:

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

    A class which was mapped by the sqlalchemy.ext.declarative extension will also have its mapper available via the __mapper__ attribute.

    Class signature

    class (sqlalchemy.orm.ORMFromClauseRole, sqlalchemy.orm.ORMEntityColumnsClauseRole, sqlalchemy.sql.traversals.MemoizedHasCacheKey, 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, 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 object.

      This constructor is mirrored as a public API function; see sqlalchemy.orm.mapper() for a full usage and argument description.

    • method (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 all_orm_descriptors

      A namespace of all InspectionAttr attributes associated with the mapped class.

      These attributes are in all cases Python associated with the mapped class or its superclasses.

      To distinguish between mapped attributes and extension attributes, the attribute InspectionAttr.extension_type will refer to a constant that distinguishes between different extension types.

      The sorting of the attributes is based on the following rules:

      1. Iterate through the class and its superclasses in order from subclass to superclass (i.e. iterate through cls.__mro__)

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

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

      When dealing with a QueryableAttribute, the attribute refers to the MapperProperty property, which is what you get when referring to the collection of mapped properties via .

      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

    • attribute sqlalchemy.orm.Mapper.attrs

      A namespace of all 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 .

      Mapper has several pre-filtered views of this attribute which limit the types of properties returned, including , column_attrs, , and composites.

      Warning

      The 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

      Mapper.all_orm_descriptors

    • attribute base_mapper = None

      The base-most Mapper in an inheritance chain.

      In a non-inheriting scenario, this attribute will always be this . In an inheritance scenario, it references the Mapper which is parent to all other objects 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 .

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

        • 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

      Cascades

      - illustrates a generic function to traverse all objects without relying on cascades.

    • attribute sqlalchemy.orm.Mapper.class_ = None

      The Python class which this maps.

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

    • attribute sqlalchemy.orm.Mapper.class_manager = None

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

    • attribute column_attrs

      Return a namespace of all ColumnProperty properties maintained by this .

      See also

      Mapper.attrs - namespace of all objects.

    • attribute sqlalchemy.orm.Mapper.columns = None

      A collection of or other scalar expression objects maintained by this Mapper.

      The collection behaves the same as that of the c attribute on any 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 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 composites

      Return a namespace of all CompositeProperty properties maintained by this .

      See also

      Mapper.attrs - namespace of all objects.

    • attribute sqlalchemy.orm.Mapper.concrete = None

      Represent True if this is 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 = False

      Represent True if this has been configured.

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

      See also

      configure_mappers().

    • attribute 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 get_property_by_column(column)

      Given a Column object, return the which 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, is 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 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 Row instance. The columns which are mapped by this should be locatable in the row, preferably via the Column object directly (as is the case when a construct is executed), or via string names of the form <tablename>_<colname>.

    • attribute sqlalchemy.orm.Mapper.inherits = None

      References the which this Mapper inherits from, if any.

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

    • attribute is_mapper = True

      Part of the inspection API.

    • method sqlalchemy.orm.Mapper.is_sibling(other)

      return true if the other mapper is an inheriting sibling to this one. common parent but different branch

    • method 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 local_table = None

      The Selectable which this manages.

      Typically is an instance of Table or . 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 represents. If this mapper is a single-table inheriting mapper, local_table will be None.

      See also

      Mapper.persist_selectable.

    • attribute mapped_table

      Deprecated since version 1.3: Use .persist_selectable

    • attribute sqlalchemy.orm.Mapper.mapper

      Part of the inspection API.

      Returns self.

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

    • attribute persist_selectable = None

      The Selectable to which this is mapped.

      Typically an instance of Table, , or Alias.

      The 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”.

      is also separate from Mapper.local_table, which represents the set of columns that are locally mapped on this class directly.

      See also

      .

      Mapper.local_table.

    • attribute polymorphic_identity = None

      Represent an identifier which is matched against the Mapper.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 .

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

      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 or SQL expression specified as the polymorphic_on argument for this Mapper, within an inheritance scenario.

      This attribute is normally a 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.

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

      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 a , 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 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.

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

    • method primary_mapper()

      Return the primary mapper corresponding to this mapper’s class key (class).

    • attribute sqlalchemy.orm.Mapper.relationships

      A namespace of all properties maintained by this Mapper.

      Warning

      the 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 objects.

    • attribute sqlalchemy.orm.Mapper.selectable

      The FromClause construct this 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.

    • attribute 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 True if this is a single table inheritance mapper.

      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.

    • attribute synonyms

      Return a namespace of all SynonymProperty properties maintained by this .

      See also

      Mapper.attrs - namespace of all objects.

    • attribute sqlalchemy.orm.Mapper.tables = None

      An iterable containing the collection of objects which this Mapper is aware of.

      If the mapper is mapped to a , or an Alias representing a , 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.

    • attribute with_polymorphic_mappers

      The list of Mapper objects included in the default “polymorphic” query.