Class Mapping API
class sqlalchemy.orm.registry
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
sqlalchemy.orm.mapper()
classical mapping function, which is removed as of SQLAlchemy 2.0.
New in version 1.4.
Members
__init__(), , configure(), , generate_base(), , map_imperatively(), , mapped_as_dataclass(), , update_type_annotation_map()
See also
- overview of class mapping styles.
method sqlalchemy.orm.registry.__init__(*, metadata: Optional[MetaData] = None, class_registry: Optional[clsregistry._ClsRegistryType] = None, type_annotation_map: Optional[_TypeAnnotationMapType] = None, constructor: Callable[…, None] = <function _declarative_constructor>)
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. IfNone
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.
type_annotation_map –
optional dictionary of Python types to SQLAlchemy classes or instances. The provided dict will update the default type mapping. This is used exclusively by the MappedColumn construct to produce column types based on annotations within the type.
New in version 2.0.
See also
method as_declarative_base(**kw: Any) → Callable[[Type[_T]], Type[_T]]
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: bool = False) → None
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
New in version 1.4.0b2.
method dispose(cascade: bool = False) → None
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
method generate_base(mapper: ~typing.Optional[~typing.Callable[[…], ~sqlalchemy.orm.mapper.Mapper[~typing.Any]]] = None, cls: ~typing.Type[~typing.Any] = <class ‘object’>, name: str = ‘Base’, metaclass: ~typing.Type[~typing.Any] = <class ‘sqlalchemy.orm.decl_api.DeclarativeMeta’>) → Any
Generate a declarative base class.
Classes that inherit from the returned class object will be automatically mapped using declarative mapping.
E.g.:
from sqlalchemy.orm import registry
mapper_registry = registry()
Base = mapper_registry.generate_base()
class MyClass(Base):
__tablename__ = "my_table"
id = Column(Integer, primary_key=True)
The above dynamically generated class is equivalent to the non-dynamic example below:
from sqlalchemy.orm import registry
from sqlalchemy.orm.decl_api import DeclarativeMeta
mapper_registry = registry()
class Base(metaclass=DeclarativeMeta):
__abstract__ = True
registry = mapper_registry
metadata = mapper_registry.metadata
__init__ = mapper_registry.constructor
Changed in version 2.0: Note that the registry.generate_base() method is superseded by the new class, which generates a new “base” class using subclassing, rather than return value of a function. This allows an approach that is compatible with PEP 484 typing tools.
The method provides the implementation for the declarative_base() function, which creates the and base class all at once.
See the section Declarative Mapping for background and examples.
Parameters:
mapper – An optional callable, defaults to . This function is used to generate new Mapper 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.
See also
[Declarative Mapping]($aaabb163d969e4c7.md#orm-declarative-mapping)
[declarative\_base()](#sqlalchemy.orm.declarative_base "sqlalchemy.orm.declarative_base")
method map_declaratively(cls: Type[_O]) → Mapper[_O]
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.:
from sqlalchemy.orm import registry
mapper_registry = registry()
class Foo:
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)
name = Column(String)
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
- more common decorator interface to this function.
method map_imperatively(class\: Type[_O], _local_table: Optional[FromClause] = None, **kw: Any) → [_O]
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 now-removed SQLAlchemy
mapper()
function, except that it’s in terms of a particular registry.E.g.:
from sqlalchemy.orm import registry
mapper_registry = registry()
my_table = Table(
"my_table",
mapper_registry.metadata,
Column('id', Integer, primary_key=True)
)
class MyClass:
pass
mapper_registry.map_imperatively(MyClass, my_table)
See the section Imperative Mapping for complete background and usage examples.
Parameters:
class_ – The class to be mapped. Corresponds to the parameter.
local_table – the Table or other object that is the subject of the mapping. Corresponds to the Mapper.local_table parameter.
**kw – all other keyword arguments are passed to the constructor directly.
See also
[Imperative Mapping]($aaabb163d969e4c7.md#orm-imperative-mapping)
[Declarative Mapping]($aaabb163d969e4c7.md#orm-declarative-mapping)
method sqlalchemy.orm.registry.mapped(cls: Type[_O]) → Type[_O]
Class decorator that will apply the Declarative mapping process to a given class.
E.g.:
from sqlalchemy.orm import registry
mapper_registry = registry()
@mapper_registry.mapped
class Foo:
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)
name = Column(String)
See the section for complete details and examples.
Parameters:
cls – class to be mapped.
Returns:
the class that was passed.
See also
- generates a base class that will apply Declarative mapping to subclasses automatically using a Python metaclass.
See also
method mapped_as_dataclass(_registry\_cls: Optional[Type[_O]] = None, *, _init: Union[_NoArg, bool] = _NoArg.NO_ARG, repr: Union[_NoArg, bool] = _NoArg.NO_ARG, eq: Union[_NoArg, bool] = _NoArg.NO_ARG, order: Union[_NoArg, bool] = _NoArg.NO_ARG, unsafe_hash: Union[_NoArg, bool] = _NoArg.NO_ARG, match_args: Union[_NoArg, bool] = _NoArg.NO_ARG, kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG) → Union[Type[_O], Callable[[Type[_O]], Type[_O]]]
Class decorator that will apply the Declarative mapping process to a given class, and additionally convert the class to be a Python dataclass.
See also
Declarative Dataclass Mapping - complete background on SQLAlchemy native dataclass mapping
New in version 2.0.
attribute mappers
read only collection of all Mapper objects.
method update_type_annotation_map(type_annotation_map: _TypeAnnotationMapType) → None
update the registry.type_annotation_map with new values.
function sqlalchemy.orm.add_mapped_attribute(target: Type[_O], key: str, attr: [Any]) → None
Add a new mapped attribute to an ORM mapped class.
E.g.:
add_mapped_attribute(User, "addresses", relationship(Address))
This may be used for ORM mappings that aren’t using a declarative metaclass that intercepts attribute set operations.
New in version 2.0.
function sqlalchemy.orm.column_property(column: _ORMColumnExprArgument[_T], *additional_columns: _ORMColumnExprArgument[Any], group: Optional[str] = None, deferred: bool = False, raiseload: bool = False, comparator_factory: Optional[Type[PropComparator[_T]]] = None, init: Union[_NoArg, bool] = _NoArg.NO_ARG, repr: Union[_NoArg, bool] = _NoArg.NO_ARG, default: Optional[Any] = _NoArg.NO_ARG, default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, compare: Union[_NoArg, bool] = _NoArg.NO_ARG, kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, active_history: bool = False, expire_on_flush: bool = True, info: Optional[_InfoType] = None, doc: Optional[str] = None) → [_T]
Provide a column-level property for use with a mapping.
Column-based properties can normally be applied to the mapper’s properties
dictionary using the Column element directly. Use this function when the given column is not directly present within the mapper’s selectable; examples include SQL expressions, functions, and scalar SELECT queries.
The function returns an instance of ColumnProperty.
Columns that aren’t present in the mapper’s selectable won’t be persisted by the mapper and are effectively “read-only” attributes.
Parameters:
*cols – list of Column objects to be mapped.
active_history=False – When
True
, indicates that the “previous” value for a scalar attribute should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple non-primary-key scalar values only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of or Session.is_modified() which also need to know the “previous” value of the attribute.comparator_factory – a class which extends which provides custom SQL clause generation for comparison operations.
group – a group name for this property when marked as deferred.
deferred – when True, the column property is “deferred”, meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().
doc – optional string that will be applied as the doc on the class-bound descriptor.
expire_on_flush=True – Disable expiry on flush. A column_property() which refers to a SQL expression (and not a single table-bound column) is considered to be a “read only” property; populating it has no effect on the state of data, and it can only return database state. For this reason a column_property()’s value is expired whenever the parent object is involved in a flush, that is, has any kind of “dirty” state within a flush. Setting this parameter to
False
will have the effect of leaving any existing value present after the flush proceeds. Note that the with default expiration settings still expires all attributes after a Session.commit() call, however.info – Optional data dictionary which will be populated into the attribute of this object.
raiseload –
if True, indicates the column should raise an error when undeferred, rather than loading the value. This can be altered at query time by using the deferred() option with raiseload=False.
New in version 1.4.
See also
See also
Applying Load, Persistence and Mapping Options for Mapped Table Columns - to map columns while including mapping options
- to map SQL expressions
function sqlalchemy.orm.declarative_base(*, metadata: Optional[MetaData] = None, mapper: Optional[Callable[…, Mapper[Any]]] = None, cls: Type[Any] = <class ‘object’>, name: str = ‘Base’, class_registry: Optional[clsregistry._ClsRegistryType] = None, type_annotation_map: Optional[_TypeAnnotationMapType] = None, constructor: Callable[…, None] = <function _declarative_constructor>, metaclass: Type[Any] = <class ‘sqlalchemy.orm.decl_api.DeclarativeMeta’>) → Any
Construct a base class for declarative class definitions.
The new base class will be given a metaclass that produces appropriate Table objects and makes the appropriate calls based on the information provided declaratively in the class and any subclasses of the class.
Changed in version 2.0: Note that the declarative_base() function is superseded by the new class, which generates a new “base” class using subclassing, rather than return value of a function. This allows an approach that is compatible with PEP 484 typing tools.
The function is a shorthand version of using the registry.generate_base() method. That is, the following:
from sqlalchemy.orm import declarative_base
Base = declarative_base()
Is equivalent to:
from sqlalchemy.orm import registry
mapper_registry = registry()
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:
metadata – An optional instance. All Table objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The instance will be available via the
metadata
attribute of the generated declarative base class.mapper – An optional callable, defaults to Mapper. 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. IfNone
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 and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships.
type_annotation_map –
optional dictionary of Python types to SQLAlchemy TypeEngine classes or instances. This is used exclusively by the construct to produce column types based on annotations within the Mapped type.
New in version 2.0.
See also
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.declarative_mixin(cls: Type[_T]) → Type[_T]
Mark a class as providing the feature of “declarative mixin”.
E.g.:
The decorator currently does not modify the given class in any way; it’s current purpose is strictly to assist the Mypy plugin in being able to identify SQLAlchemy declarative mixin classes when no other context is present.
New in version 1.4.6.
See also
Using @declared_attr and Declarative Mixins - in the
function sqlalchemy.orm.as_declarative(**kw: Any) → Callable[[Type[_T]], Type[_T]]
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.:
from sqlalchemy.orm import as_declarative
@as_declarative()
class Base:
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(Integer, primary_key=True)
class MyMappedClass(Base):
# ...
See also
function sqlalchemy.orm.mapped_column(\_name_pos: Optional[Union[str, _TypeEngineArgument[Any], SchemaEventTarget]] = None, __type_pos: Optional[Union[_TypeEngineArgument[Any], ]] = None, *args: SchemaEventTarget, _init: Union[_NoArg, bool] = _NoArg.NO_ARG, repr: Union[_NoArg, bool] = _NoArg.NO_ARG, default: Optional[Any] = _NoArg.NO_ARG, default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, compare: Union[_NoArg, bool] = _NoArg.NO_ARG, kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, nullable: Optional[Union[bool, Literal[SchemaConst.NULL_UNSPECIFIED]]] = SchemaConst.NULL_UNSPECIFIED, primary_key: Optional[bool] = False, deferred: Union[_NoArg, bool] = _NoArg.NO_ARG, deferred_group: Optional[str] = None, deferred_raiseload: bool = False, use_existing_column: bool = False, name: Optional[str] = None, type\: Optional[_TypeEngineArgument[Any]] = None, _autoincrement: Union[bool, Literal[‘auto’, ‘ignore_fk’]] = ‘auto’, doc: Optional[str] = None, key: Optional[str] = None, index: Optional[bool] = None, unique: Optional[bool] = None, info: Optional[_InfoType] = None, onupdate: Optional[Any] = None, insert_default: Optional[Any] = _NoArg.NO_ARG, server_default: Optional[_ServerDefaultType] = None, server_onupdate: Optional[] = None, quote: Optional[bool] = None, system: bool = False, comment: Optional[str] = None, **dialect_kwargs: Any) → MappedColumn[Any]
declare a new ORM-mapped construct for use within Declarative Table configuration.
The function provides an ORM-aware and Python-typing-compatible construct which is used with declarative mappings to indicate an attribute that’s mapped to a Core object. It provides the equivalent feature as mapping an attribute to a Column object directly when using Declarative, specifically when using configuration.
New in version 2.0.
mapped_column() is normally used with explicit typing along with the annotation type, where it can derive the SQL type and nullability for the column based on what’s present within the Mapped annotation. It also may be used without annotations as a drop-in replacement for how is used in Declarative mappings in SQLAlchemy 1.x style.
For usage examples of mapped_column(), see the documentation at .
See also
Declarative Table with mapped_column() - complete documentation
- migration notes for Declarative mappings using 1.x style mappings
Parameters:
__name – String name to give to the Column. This is an optional, positional only argument that if present must be the first positional argument passed. If omitted, the attribute name to which the is mapped will be used as the SQL column name.
__type – TypeEngine type or instance which will indicate the datatype to be associated with the . This is an optional, positional-only argument that if present must immediately follow the
__name
parameter if present also, or otherwise be the first positional parameter. If omitted, the ultimate type for the column may be derived either from the annotated type, or if a ForeignKey is present, from the datatype of the referenced column.*args – Additional positional arguments include constructs such as , CheckConstraint, and , which are passed through to the constructed Column.
primary_key – optional bool, indicates the would be part of the table’s primary key or not.
deferred –
Optional bool - this keyword argument is consumed by the ORM declarative process, and is not part of the Column itself; instead, it indicates that this column should be “deferred” for loading as though mapped by .
See also
deferred_group –
Implies to
True
, and set the deferred.group parameter.See also
deferred_raiseload –
Implies mapped_column.deferred to
True
, and set the parameter.See also
use_existing_column –
if True, will attempt to locate the given column name on an inherited superclass (typically single inheriting superclass), and if present, will not produce a new column, mapping to the superclass column as though it were omitted from this class. This is used for mixins that add new columns to an inherited superclass.
See also
New in version 2.0.0b4.
default –
Passed directly to the Column.default parameter if the parameter is not present. Additionally, when used with Declarative Dataclass Mapping, indicates a default Python value that should be applied to the keyword constructor within the generated
__init__()
method.Note that in the case of dataclass generation when is not present, this means the mapped_column.default value is used in two places, both the
__init__()
method as well as the parameter. While this behavior may change in a future release, for the moment this tends to “work out”; a default ofNone
will mean that the Column gets no default generator, whereas a default that refers to a non-None
Python or SQL expression value will be assigned up front on the object when__init__()
is called, which is the same value that the Core construct would use in any case, leading to the same end result.insert_default – Passed directly to the Column.default parameter; will supersede the value of when present, however mapped_column.default will always apply to the constructor default for a dataclasses mapping.
init – Specific to , specifies if the mapped attribute should be part of the
__init__()
method as generated by the dataclass process.repr – Specific to Declarative Dataclass Mapping, specifies if the mapped attribute should be part of the
__repr__()
method as generated by the dataclass process.default_factory – Specific to , specifies a default-value generation function that will take place as part of the
__init__()
method as generated by the dataclass process.compare –
Specific to Declarative Dataclass Mapping, indicates if this field should be included in comparison operations when generating the
__eq__()
and__ne__()
methods for the mapped class.New in version 2.0.0b4.
kw_only – Specific to , indicates if this field should be marked as keyword-only when generating the
__init__()
.**kw – All remaining keyword argments are passed through to the constructor for the Column.
class sqlalchemy.orm.declared_attr
Mark a class-level method as representing the definition of a mapped property or Declarative directive.
is typically applied as a decorator to a class level method, turning the attribute into a scalar-like property that can be invoked from the uninstantiated class. The Declarative mapping process looks for these declared_attr callables as it scans classes, and assumes any attribute marked with will be a callable that will produce an object specific to the Declarative mapping or table configuration.
Example:
class ProvidesUserMixin:
"A mixin that adds a 'user' relationship to classes."
user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id"))
@declared_attr
return relationship("User")
When used with Declarative directives such as __tablename__
, the declared_attr.directive() modifier may be used which indicates to typing tools that the given method is not dealing with Mapped attributes:
class CreateTableName:
@declared_attr.directive
def __tablename__(cls) -> str:
return cls.__name__.lower()
can also be applied directly to mapped classes, to allow for attributes that dynamically configure themselves on subclasses when using mapped inheritance schemes. Below illustrates declared_attr to create a dynamic scheme for generating the parameter for subclasses:
class Employee(Base):
__tablename__ = 'employee'
id: Mapped[int] = mapped_column(primary_key=True)
type: Mapped[str] = mapped_column(String(50))
@declared_attr.directive
def __mapper_args__(cls) -> dict[str, Any]:
if cls.__name__ == 'Employee':
return {
"polymorphic_on":cls.type,
"polymorphic_identity":"Employee"
}
else:
return {"polymorphic_identity":cls.__name__}
class Engineer(Employee):
pass
declared_attr supports decorating functions that are explicitly decorated with @classmethod
. This is never necessary from a runtime perspective, however may be needed in order to support typing tools that don’t otherwise recognize the decorated function as having class-level behaviors for the cls
parameter:
class SomethingMixin:
x: Mapped[int]
y: Mapped[int]
@declared_attr
@classmethod
def x_plus_y(cls) -> Mapped[int]:
return column_property(cls.x + cls.y)
New in version 2.0: - declared_attr can accommodate a function decorated with @classmethod
to help with integration where needed.
See also
Composing Mapped Hierarchies with Mixins - Declarative Mixin documentation with background on use patterns for .
Members
Class signature
class sqlalchemy.orm.declared_attr (sqlalchemy.orm.base._MappedAttribute
, sqlalchemy.orm.decl_api._declared_attr_common
)
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
__abstract__
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:``` class HasIdMixin:
@declared_attr.cascading
def id(cls):
if has_inherited_table(cls):
return Column(ForeignKey("myclass.id"), primary_key=True)
else:
return Column(Integer, primary_key=True)
class MyClass(HasIdMixin, Base):
__tablename__ = "myclass"
# ...
class MySubClass(MyClass):
""" """
# ...
```
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
[Declarative Inheritance](https://docs.sqlalchemy.org/en/20/orm/extensions/declarative/inheritance.html#declarative-inheritance)
[Using \_orm.declared\_attr() to generate table-specific inheriting columns]($de76f3ae44287f81.md#mixin-inheritance-columns)
attribute directive
Mark a declared_attr as decorating a Declarative directive such as
__tablename__
or__mapper_args__
.The purpose of is strictly to support PEP 484 typing tools, by allowing the decorated function to have a return type that is not using the generic class, as would normally be the case when declared_attr is used for columns and mapped properties. At runtime, the returns the declared_attr class unmodified.
E.g.:
class CreateTableName:
@declared_attr.directive
def __tablename__(cls) -> str:
return cls.__name__.lower()
New in version 2.0.
See also
class sqlalchemy.orm.DeclarativeBase
Base class used for declarative class definitions.
The allows for the creation of new declarative bases in such a way that is compatible with type checkers:
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
The above Base
class is now usable as the base for new declarative mappings. The superclass makes use of the __init_subclass__()
method to set up new classes and metaclasses aren’t used.
When first used, the DeclarativeBase class instantiates a new to be used with the base, assuming one was not provided explicitly. The DeclarativeBase class supports class-level attributes which act as parameters for the construction of this registry; such as to indicate a specific collection as well as a specific value for registry.type_annotation_map:
from typing import Annotation
from sqlalchemy import BigInteger
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase
bigint = Annotation(int, "bigint")
my_metadata = MetaData()
class Base(DeclarativeBase):
metadata = my_metadata
type_annotation_map = {
str: String().with_variant(String(255), "mysql", "mariadb"),
bigint: BigInteger()
}
Class-level attributes which may be specified include:
Parameters:
metadata – optional collection. If a registry is constructed automatically, this collection will be used to construct it. Otherwise, the local MetaData collection will supercede that used by an existing passed using the DeclarativeBase.registry parameter.
type_annotation_map – optional type annotation map that will be passed to the as registry.type_annotation_map.
registry – supply a pre-existing directly.
New in version 2.0: Added DeclarativeBase, so that declarative base classes may be constructed in such a way that is also recognized by type checkers. As a result, DeclarativeBase and other subclassing-oriented APIs should be seen as superseding previous “class returned by a function” APIs, namely and registry.generate_base(), where the base class returned cannot be recognized by type checkers without using plugins.
Members
, __mapper_args__, , __table_args__, , metadata,
Class signature
class sqlalchemy.orm.DeclarativeBase (sqlalchemy.inspection.Inspectable
)
attribute __mapper__: ClassVar[Mapper[Any]]
The object to which a particular class is mapped.
May also be acquired using inspect(), e.g.
inspect(klass)
.attribute __mapper_args__: Any
Dictionary of arguments which will be passed to the Mapper constructor.
See also
attribute sqlalchemy.orm.DeclarativeBase.__table__: ClassVar[]
The FromClause to which a particular subclass is mapped.
This is usually an instance of but may also refer to other kinds of FromClause such as , depending on how the class is mapped.
See also
attribute __table_args__: Any
A dictionary or tuple of arguments that will be passed to the Table constructor. See for background on the specific structure of this collection.
See also
attribute __tablename__: Any
String name to assign to the generated Table object, if not specified directly via .
See also
attribute metadata: ClassVar[MetaData]
Refers to the collection that will be used for new Table objects.
See also
attribute sqlalchemy.orm.DeclarativeBase.registry: ClassVar[]
Refers to the registry in use where new objects will be associated.
class sqlalchemy.orm.DeclarativeBaseNoMeta
Same as DeclarativeBase, but does not use a metaclass to intercept new attributes.
The base may be used when use of custom metaclasses is desirable.
New in version 2.0.
Members
__mapper__, , __table__, , __tablename__, , registry
Class signature
class (sqlalchemy.inspection.Inspectable
)
attribute sqlalchemy.orm.DeclarativeBaseNoMeta.__mapper__: ClassVar[[Any]]
The Mapper object to which a particular class is mapped.
May also be acquired using , e.g.
inspect(klass)
.attribute sqlalchemy.orm.DeclarativeBaseNoMeta.__mapper_args__: Any
Dictionary of arguments which will be passed to the constructor.
See also
attribute __table__: Optional[FromClause]
The to which a particular subclass is mapped.
This is usually an instance of Table but may also refer to other kinds of such as Subquery, depending on how the class is mapped.
See also
attribute sqlalchemy.orm.DeclarativeBaseNoMeta.__table_args__: Any
A dictionary or tuple of arguments that will be passed to the constructor. See Declarative Table Configuration for background on the specific structure of this collection.
See also
attribute sqlalchemy.orm.DeclarativeBaseNoMeta.__tablename__: Any
String name to assign to the generated object, if not specified directly via DeclarativeBase.__table__.
See also
attribute sqlalchemy.orm.DeclarativeBaseNoMeta.metadata: ClassVar[]
Refers to the MetaData collection that will be used for new objects.
See also
attribute registry: ClassVar[registry]
Refers to the in use where new Mapper objects will be associated.
function sqlalchemy.orm.has_inherited_table(cls: Type[_O]) → bool
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: str, map_column: bool = False) → Callable[[Callable[[…], Any]], Synonym[Any]]
Decorator that produces an attribute in conjunction with a Python descriptor.
The function being decorated is passed to synonym() as the parameter:
The hybrid properties feature of SQLAlchemy is typically preferred instead of synonyms, which is a more legacy feature.
See also
- Overview of synonyms
synonym() - the mapper-level function
- The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than can be achieved with synonyms.
function sqlalchemy.orm.object_mapper(instance: _T) → Mapper[_T]
Given an object, return the primary Mapper associated with the object instance.
Raises 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.
function sqlalchemy.orm.class_mapper(class\: Type[_O], _configure: bool = True) → [_O]
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:
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() → None
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(class\: Optional[Type[_T]] = None, _ident: Union[Any, Tuple[Any, …]] = None, *, instance: Optional[_T] = None, row: Optional[Union[[Any], RowMapping]] = None, identity_token: Optional[Any] = None) → _IdentityKeyType[_T]
Generate “identity key” tuples, as are used as keys in the 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 or RowMapping object.
E.g.:
text("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:
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.
function sqlalchemy.orm.reconstructor(fn)
Decorate a method as the ‘reconstructor’ hook.
Designates a single method as the “reconstructor”, an __init__
-like method that will be called by the ORM after the instance has been loaded from the database or otherwise reconstituted.
Tip
The reconstructor() decorator makes use of the event hook, which can be used directly.
The reconstructor will be invoked with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative.
See also
class sqlalchemy.orm.Mapper
Defines an association between a Python class and a database table or other relational structure, so that ORM operations against the class may proceed.
The object is instantiated using mapping methods present on the registry object. For information about instantiating new objects, see ORM Mapped Class Overview.
Members
, add_properties(), , all_orm_descriptors, , base_mapper, , cascade_iterator(), , class_manager, , columns, , composites, , configured, , get_property(), , identity_key_from_instance(), , identity_key_from_row(), , is_mapper, , isa(), , local_table, , mapper, , persist_selectable, , polymorphic_iterator(), , polymorphic_on, , primary_key_from_instance(), , relationships, , self_and_descendants, , synonyms, , validators,
Class signature
class sqlalchemy.orm.Mapper (sqlalchemy.orm.ORMFromClauseRole
, sqlalchemy.orm.ORMEntityColumnsClauseRole
, sqlalchemy.sql.cache_key.MemoizedHasCacheKey
, , sqlalchemy.log.Identified, sqlalchemy.inspection.Inspectable
, sqlalchemy.event.registry.EventTarget
, typing.Generic
)
method __init__(class\: Type[_O], _local_table: Optional[FromClause] = None, properties: Optional[Mapping[str, [Any]]] = None, primary_key: Optional[Iterable[_ORMColumnExprArgument[Any]]] = None, non_primary: bool = False, inherits: Optional[Union[Mapper[Any], Type[Any]]] = None, inherit_condition: Optional[_ColumnExpressionArgument[bool]] = None, inherit_foreign_keys: Optional[[_ORMColumnExprArgument[Any]]] = None, always_refresh: bool = False, version_id_col: Optional[_ORMColumnExprArgument[Any]] = None, version_id_generator: Optional[Union[Literal[False], Callable[[Any], Any]]] = None, polymorphic_on: Optional[Union[_ORMColumnExprArgument[Any], str, MapperProperty[Any]]] = None, _polymorphic_map: Optional[Dict[Any, [Any]]] = None, polymorphic_identity: Optional[Any] = None, concrete: bool = False, with_polymorphic: Optional[_WithPolymorphicArg] = None, polymorphic_abstract: bool = False, polymorphic_load: Optional[Literal[‘selectin’, ‘inline’]] = None, allow_partial_pks: bool = True, batch: bool = True, column_prefix: Optional[str] = None, include_properties: Optional[Sequence[str]] = None, exclude_properties: Optional[[str]] = None, passive_updates: bool = True, passive_deletes: bool = False, confirm_deleted_rows: bool = True, eager_defaults: Literal[True, False, ‘auto’] = ‘auto’, legacy_is_orphan: bool = False, _compiled_cache_size: int = 100)
Direct constructor for a new Mapper object.
The constructor is not called directly, and is normally invoked through the use of the registry object through either the or Imperative mapping styles.
Changed in version 2.0: The public facing
mapper()
function is removed; for a classical mapping configuration, use the method.Parameters documented below may be passed to either the registry.map_imperatively() method, or may be passed in the
__mapper_args__
declarative class attribute described at .Parameters:
class_ – The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself.
local_table – The Table or other (i.e. 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 DeclarativeBase.__table__ attribute or via the produced as a result of the DeclarativeBase.__tablename__ attribute being present.polymorphic_abstract –
Indicates this class will be mapped in a polymorphic hierarchy, but not directly instantiated. The class is mapped normally, except that it has no requirement for a within an inheritance hierarchy. The class however must be part of a polymorphic inheritance scheme which uses Mapper.polymorphic_on at the base.
New in version 2.0.
See also
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 Column objects that are mapped explicitly in the dictionary.
This parameter is typically useful with imperative mappings that keep the Table object separate. Below, assuming the
user_table
object has columns nameduser_id
,user_name
, andpassword
:class User(Base):
__table__ = user_table
The above mapping will assign the
user_id
,user_name
, andpassword
columns to attributes named_user_id
,_user_name
, and_password
on the mappedUser
class.The Mapper.column_prefix parameter is uncommon in modern use. For dealing with reflected tables, a more flexible approach to automating a naming scheme is to intercept the objects as they are reflected; see the section Automating Column Naming Schemes from Reflected Tables for notes on this usage pattern.
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.
The fetch of values occurs either by using
RETURNING
inline with theINSERT
orUPDATE
statement, or by adding an additionalSELECT
statement subsequent to theINSERT
orUPDATE
, if the backend does not supportRETURNING
.The use of
RETURNING
is extremely performant in particular forINSERT
statements where SQLAlchemy can take advantage of insertmanyvalues, whereas the use of an additionalSELECT
is relatively poor performing, adding additional SQL round trips which would be unnecessary if these new attributes are not to be accessed in any case.For this reason, defaults to the string value
"auto"
, which indicates that server defaults for INSERT should be fetched usingRETURNING
if the backing database supports it and if the dialect in use supports “insertmanyreturning” for an INSERT statement. If the backing database does not supportRETURNING
or “insertmanyreturning” is not available, server defaults will not be fetched.Changed in version 2.0.0rc1: added the “auto” option for Mapper.eager_defaults
See also
Changed in version 0.9.0: The
eager_defaults
option can now make use of RETURNING for backends which support it.Changed in version 2.0.0: RETURNING now works with multiple rows INSERTed at once using the feature, which among other things allows the Mapper.eager_defaults feature to be very performant on supporting backends.
exclude_properties –
A list or set of string column names to be excluded from mapping.
See also
include_properties –
An inclusive list or set of string column names to map.
See also
inherits –
A mapped class or the corresponding of one indicating a superclass to which this Mapper 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
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 ForeignKey configuration, 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 owning only when it is de-associated from all parents that specify adelete-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 specifydelete-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 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
is in addition to the “primary” mapper, that is, the one used for persistence. The Mapper 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 –
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()
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
- 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:
New in version 1.2.
See also
polymorphic_on –
Specifies the column, attribute, or SQL expression used to determine the target class for an incoming row, when inheriting classes are present.
May be specified as a string attribute name, or as a SQL expression such as a or in a Declarative mapping a mapped_column() object. It is typically expected that the SQL expression corresponds to a column in the base-most mapped :
class Employee(Base):
__tablename__ = 'employee'
id: Mapped[int] = mapped_column(primary_key=True)
discriminator: Mapped[str] = mapped_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: Mapped[int] = mapped_column(primary_key=True)
discriminator: Mapped[str] = mapped_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 using its string name, which is of particular use when using annotated column configurations:
class Employee(Base):
__tablename__ = 'employee'
id: Mapped[int] = mapped_column(primary_key=True)
discriminator: Mapped[str]
__mapper_args__ = {
"polymorphic_on": "discriminator",
"polymorphic_identity": "employee"
}
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:from sqlalchemy import event
from sqlalchemy.orm import object_mapper
@event.listens_for(Employee, "init", propagate=True)
def set_identity(instance, *arg, **kw):
mapper = object_mapper(instance)
instance.discriminator = mapper.polymorphic_identity
Where above, we assign the value of
polymorphic_identity
for the mapped class to thediscriminator
attribute, thus persisting the value to thediscriminator
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
polymorphic_identity –
Specifies the value which identifies this particular class as returned by the column expression referred to by the setting. As rows are received, the value corresponding to the Mapper.polymorphic_on column expression is compared to this value, indicating which subclass should be used for the newly reconstructed object.
See also
properties –
A dictionary mapping the string names of object attributes to MapperProperty instances, which define the persistence behavior of that attribute. Note that objects present in the mapped Table are automatically placed into
ColumnProperty
instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those instances declared in the declared class body.See also
The properties dictionary - in the
primary_key –
A list of Column 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.See also
- background and example use
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: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
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.The parameter may be preferable over the use of Mapper.with_polymorphic in modern mappings to indicate a per-subclass technique of indicating polymorphic loading styles.
See also
method sqlalchemy.orm.Mapper.add_properties(dict_of_properties)
Add the given dictionary of properties to this mapper, using add_property.
method add_property(key: str, prop: Union[Column[Any], [Any]]) → None
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 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 . This includes QueryableAttribute, as well as extension types such as , hybrid_method and .
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:
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 .
When dealing with a QueryableAttribute, the
QueryableAttribute.property
attribute refers to the property, which is what you get when referring to the collection of mapped properties via Mapper.attrs.Warning
The accessor namespace is an instance of
OrderedProperties
. 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 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 hasUser.name
attribute would providemapper.attrs.name
, which would be the representing thename
column. The namespace object can also be iterated, which would yield each MapperProperty.has several pre-filtered views of this attribute which limit the types of properties returned, including synonyms, , relationships, and .
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 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: [Any]
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: ReadOnlyColumnCollection[str, [Any]]
A synonym for Mapper.columns.
method cascade_iterator(type\: str, _state: InstanceState[_O], halt_on: Optional[Callable[[[Any]], bool]] = None) → Iterator[Tuple[object, [Any], InstanceState[Any], _InstanceDict]]
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
- illustrates a generic function to traverse all objects without relying on cascades.
attribute sqlalchemy.orm.Mapper.class_: Type[_O]
The class to which this is mapped.
attribute sqlalchemy.orm.Mapper.class_manager: [_O]
The ClassManager which maintains event listeners and class-bound descriptors for this .
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 properties maintained by this Mapper.
See also
- namespace of all MapperProperty objects.
attribute columns: ReadOnlyColumnCollection[str, Column[Any]]
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 thekey
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: [Any]) → bool
Return true if the given mapper shares a common inherited parent as this mapper.
attribute sqlalchemy.orm.Mapper.composites
Return a namespace of all properties maintained by this Mapper.
See also
- namespace of all MapperProperty objects.
attribute concrete: bool
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.
attribute configured: bool = False
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
.
attribute sqlalchemy.orm.Mapper.entity
Part of the inspection API.
Returns self.class_.
method get_property(key: str, _configure_mappers: bool = True) → MapperProperty[Any]
return a MapperProperty associated with the given key.
method get_property_by_column(column: ColumnElement[_T]) → [_T]
Given a Column object, return the which maps this column.
method sqlalchemy.orm.Mapper.identity_key_from_instance(instance: _O) → _IdentityKeyType[_O]
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: [Any, …], identity_token: Optional[Any] = None) → _IdentityKeyType[_O]
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: Optional[Union[[Any], RowMapping]], identity_token: Optional[Any] = None, adapter: Optional[ORMAdapter] = None) → _IdentityKeyType[_O]
Return an identity-map key for use in storing/retrieving an item from the identity map.
Parameters:
row –
A or RowMapping produced from a result set that selected from the ORM mapped primary key columns.
Changed in version 2.0: or RowMapping are accepted for the “row” argument
attribute inherits: Optional[Mapper[Any]]
References the which this Mapper inherits from, if any.
attribute is_mapper = True
Part of the inspection API.
method sqlalchemy.orm.Mapper.is_sibling(other: [Any]) → bool
return true if the other mapper is an inheriting sibling to this one. common parent but different branch
method sqlalchemy.orm.Mapper.isa(other: [Any]) → bool
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: FromClause
The immediate which this Mapper refers towards.
Typically is an instance of , may be any FromClause.
The “local” table is the selectable that the is directly responsible for managing from an attribute access and flush perspective. For non-inheriting mappers, Mapper.local_table will be the same as . For inheriting mappers, Mapper.local_table refers to the specific portion of that includes the columns to which this Mapper is loading/persisting, such as a particular within a join.
See also
.
attribute sqlalchemy.orm.Mapper.mapped_table
Deprecated since version 1.3: Use .persist_selectable
attribute mapper
Part of the inspection API.
Returns self.
attribute sqlalchemy.orm.Mapper.non_primary: bool
Represent
True
if this 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 sqlalchemy.orm.Mapper.persist_selectable:
The FromClause to which this is mapped.
Typically is an instance of Table, may be any .
The Mapper.persist_selectable is similar to , but represents the FromClause that represents the inheriting class hierarchy overall in an inheritance scenario.
:attr.`.Mapper.persist_selectable` is also separate from the attribute, the latter of which may be an alternate subquery used for selecting columns. :attr.`.Mapper.persist_selectable` is oriented towards columns that will be written on a persist operation.
See also
.
attribute sqlalchemy.orm.Mapper.polymorphic_identity: Optional[Any]
Represent an identifier which is matched against the 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 Mapper.polymorphic_on.
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
method polymorphic_iterator() → Iterator[Mapper[Any]]
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: Dict[Any, Mapper[Any]]
A mapping of “polymorphic identity” identifiers mapped to instances, 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 polymorphic_on: Optional[KeyedColumnElement[Any]]
The Column or SQL expression specified as the
polymorphic_on
argument for this , within an inheritance scenario.This attribute is normally a Column instance but may also be an expression, such as one derived from .
This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.
attribute sqlalchemy.orm.Mapper.primary_key: [Column[Any], …]
An iterable containing the collection of objects which comprise the ‘primary key’ of the mapped table, from the perspective of this Mapper.
This list is against the selectable in . 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 .
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 considers 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: _O) → Tuple[Any, …]
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, is raised.
method sqlalchemy.orm.Mapper.primary_mapper() → [Any]
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 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 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: bool
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 Synonym properties maintained by this .
See also
Mapper.attrs - namespace of all objects.
attribute sqlalchemy.orm.Mapper.tables: [TableClause]
A sequence containing the collection of or
TableClause
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 validators: util.immutabledict[str, Tuple[str, Dict[str, Any]]]
An immutable dictionary of attributes which have been decorated using the decorator.
The dictionary contains string attribute names as keys mapped to the actual validation method.
class sqlalchemy.orm.MappedAsDataclass
Mixin class to indicate when mapping this class, also convert it to be a dataclass.
See also
Declarative Dataclass Mapping - complete background on SQLAlchemy native dataclass mapping
New in version 2.0.
class sqlalchemy.orm.MappedClassProtocol
A protocol representing a SQLAlchemy mapped class.
The protocol is generic on the type of class, use MappedClassProtocol[Any]
to allow any mapped class.
Class signature
class (typing.Protocol
)