ORM Mapped Class Overview

    For readers new to the SQLAlchemy ORM and/or new to Python in general, it’s recommended to browse through the ORM Quick Start and preferably to work through the , where ORM configuration is first introduced at Using ORM Declarative Forms to Define Table Metadata.

    SQLAlchemy features two distinct styles of mapper configuration, which then feature further sub-options for how they are set up. The variability in mapper styles is present to suit a varied list of developer preferences, including the degree of abstraction of a user-defined class from how it is to be mapped to relational schema tables and columns, what kinds of class hierarchies are in use, including whether or not custom metaclass schemes are present, and finally if there are other class-instrumentation approaches present such as if Python dataclasses are in use simultaneously.

    In modern SQLAlchemy, the difference between these styles is mostly superficial; when a particular SQLAlchemy configurational style is used to express the intent to map a class, the internal process of mapping the class proceeds in mostly the same way for each, where the end result is always a user-defined class that has a configured against a selectable unit, typically represented by a Table object, and the class itself has been to include behaviors linked to relational operations both at the level of the class as well as on instances of that class. As the process is basically the same in all cases, classes mapped from different styles are always fully interoperable with each other. The protocol MappedClassProtocol can be used to indicate a mapped class when using type checkers such as mypy.

    The original mapping API is commonly referred to as “classical” style, whereas the more automated style of mapping is known as “declarative” style. SQLAlchemy now refers to these two mapping styles as imperative mapping and declarative mapping.

    Regardless of what style of mapping used, all ORM mappings as of SQLAlchemy 1.4 originate from a single object known as , which is a registry of mapped classes. Using this registry, a set of mapper configurations can be finalized as a group, and classes within a particular registry may refer to each other by name within the configurational process.

    Changed in version 1.4: Declarative and classical mapping are now referred to as “declarative” and “imperative” mapping, and are unified internally, all originating from the registry construct that represents a collection of related mappings.

    The Declarative Mapping is the typical way that mappings are constructed in modern SQLAlchemy. The most common pattern is to first construct a base class using the DeclarativeBase superclass. The resulting base class, when subclassed will apply the declarative mapping process to all subclasses that derive from it, relative to a particular that is local to the new base by default. The example below illustrates the use of a declarative base which is then used in a declarative table mapping:

    Above, the DeclarativeBase class is used to generate a new base class (within SQLAlchemy’s documentation it’s typically referred towards as , however can have any desired name) from which new classes to be mapped may inherit from, as above a new mapped class User is constructed.

    Changed in version 2.0: The superclass supersedes the use of the declarative_base() function and methods; the superclass approach integrates with PEP 484 tools without the use of plugins. See for migration notes.

    The base class refers to a registry object that maintains a collection of related mapped classes. as well as to a object that retains a collection of Table objects to which the classes are mapped.

    The major Declarative mapping styles are further detailed in the following sections:

    Within the scope of a Declarative mapped class, there are also two varieties of how the metadata may be declared. These include:

    • Declarative Table with mapped_column() - table columns are declared inline within the mapped class using the directive (or in legacy form, using the Column object directly). The directive may also be optionally combined with type annotations using the Mapped class which can provide some details about the mapped columns directly. The column directives, in combination with the __tablename__ and optional __table_args__ class level directives will allow the Declarative mapping process to construct a object to be mapped.

    • Declarative with Imperative Table (a.k.a. Hybrid Declarative) - Instead of specifying table name and attributes separately, an explicitly constructed object is associated with a class that is otherwise mapped declaratively. This style of mapping is a hybrid of “declarative” and “imperative” mapping, and applies to techniques such as mapping classes to reflected objects, as well as mapping classes to existing Core constructs such as joins and subqueries.

    Documentation for Declarative mapping continues at Mapping Classes with Declarative.

    Imperative Mapping

    An imperative or classical mapping refers to the configuration of a mapped class using the registry.map_imperatively() method, where the target class does not include any declarative class attributes.

    Tip

    The imperative mapping form is a lesser-used form of mapping that originates from the very first releases of SQLAlchemy in 2006. It’s essentially a means of bypassing the Declarative system to provide a more “barebones” system of mapping, and does not offer modern features such as support. As such, most documentation examples use Declarative forms, and it’s recommended that new users start with Declarative Table configuration.

    Changed in version 2.0: The method is now used to create classical mappings. The sqlalchemy.orm.mapper() standalone function is effectively removed.

    In “classical” form, the table metadata is created separately with the Table construct, then associated with the User class via the method, after establishing a registry instance. Normally, a single instance of shared for all mapped classes that are related to each other:

    1. from sqlalchemy import Table, Column, Integer, String, ForeignKey
    2. from sqlalchemy.orm import registry
    3. mapper_registry = registry()
    4. user_table = Table(
    5. "user",
    6. mapper_registry.metadata,
    7. Column("id", Integer, primary_key=True),
    8. Column("name", String(50)),
    9. Column("fullname", String(50)),
    10. Column("nickname", String(12)),
    11. )
    12. class User:
    13. pass
    14. mapper_registry.map_imperatively(User, user_table)

    Information about mapped attributes, such as relationships to other classes, are provided via the properties dictionary. The example below illustrates a second Table object, mapped to a class called Address, then linked to User via :

    1. address = Table(
    2. "address",
    3. metadata_obj,
    4. Column("id", Integer, primary_key=True),
    5. Column("user_id", Integer, ForeignKey("user.id")),
    6. Column("email_address", String(50)),
    7. mapper_registry.map_imperatively(
    8. User,
    9. user,
    10. properties={
    11. "addresses": relationship(Address, backref="user", order_by=address.c.id)
    12. },
    13. )
    14. mapper_registry.map_imperatively(Address, address)

    Note that classes which are mapped with the Imperative approach are fully interchangeable with those mapped with the Declarative approach. Both systems ultimately create the same configuration, consisting of a Table, user-defined class, linked together with a object. When we talk about “the behavior of Mapper”, this includes when using the Declarative system as well - it’s still used, just behind the scenes.

    With all mapping forms, the mapping of the class can be configured in many ways by passing construction arguments that ultimately become part of the Mapper object via its constructor. The parameters that are delivered to originate from the given mapping form, including parameters passed to registry.map_imperatively() for an Imperative mapping, or when using the Declarative system, from a combination of the table columns, SQL expressions and relationships being mapped along with that of attributes such as .

    This is a class that we construct in our application. There are generally no restrictions on the structure of this class. When a Python class is mapped, there can only be one Mapper object for the class.

    When mapping with the declarative mapping style, the class to be mapped is either a subclass of the declarative base class, or is handled by a decorator or function such as .

    When mapping with the imperative style, the class is passed directly as the argument.

    The table, or other from clause object

    In the vast majority of common cases this is an instance of . For more advanced use cases, it may also refer to any kind of FromClause object, the most common alternative objects being the and Join object.

    When mapping with the mapping style, the subject table is either generated by the declarative system based on the attribute and the Column objects presented, or it is established via the __table__ attribute. These two styles of configuration are presented at and Declarative with Imperative Table (a.k.a. Hybrid Declarative).

    When mapping with the style, the subject table is passed positionally as the map_imperatively.local_table argument.

    In contrast to the “one mapper per class” requirement of a mapped class, the or other FromClause object that is the subject of the mapping may be associated with any number of mappings. The applies modifications directly to the user-defined class, but does not modify the given Table or other in any way.

    This is a dictionary of all of the attributes that will be associated with the mapped class. By default, the generates entries for this dictionary derived from the given Table, in the form of objects which each refer to an individual Column of the mapped table. The properties dictionary will also contain all the other kinds of objects to be configured, most commonly instances generated by the relationship() construct.

    When mapping with the mapping style, the properties dictionary is generated by the declarative system by scanning the class to be mapped for appropriate attributes. See the section Defining Mapped Properties with Declarative for notes on this process.

    When mapping with the style, the properties dictionary is passed directly as the properties parameter to registry.map_imperatively(), which will pass it along to the parameter.

    Other mapper configuration parameters

    When mapping with the mapping style, additional mapper configuration arguments are configured via the __mapper_args__ class attribute. Examples of use are available at Mapper Configuration Options with Declarative.

    When mapping with the style, keyword arguments are passed to the to registry.map_imperatively() method which passes them along to the class.

    The full range of parameters accepted are documented at Mapper.

    Across all styles of mapping using the registry object, the following behaviors are common:

    The registry applies a default constructor, i.e. __init__ method, to all mapped classes that don’t explicitly have their own __init__ method. The behavior of this method is such that it provides a convenient keyword constructor that will accept as optional keyword arguments all the attributes that are named. E.g.:

    1. from sqlalchemy.orm import DeclarativeBase
    2. from sqlalchemy.orm import Mapped
    3. from sqlalchemy.orm import mapped_column
    4. class Base(DeclarativeBase):
    5. pass
    6. class User(Base):
    7. __tablename__ = "user"
    8. id: Mapped[int] = mapped_column(primary_key=True)
    9. name: Mapped[str]
    10. fullname: Mapped[str]

    An object of type User above will have a constructor which allows User objects to be created as:

    1. u1 = User(name="some name", fullname="some fullname")

    Tip

    The feature provides an alternate means of generating a default __init__() method by using Python dataclasses, and allows for a highly configurable constructor form.

    A class that includes an explicit __init__() method will maintain that method, and no default constructor will be applied.

    To change the default constructor used, a user-defined Python callable may be provided to the registry.constructor parameter which will be used as the default constructor.

    The constructor also applies to imperative mappings:

    1. from sqlalchemy.orm import registry
    2. mapper_registry = registry()
    3. user_table = Table(
    4. "user",
    5. mapper_registry.metadata,
    6. Column("id", Integer, primary_key=True),
    7. Column("name", String(50)),
    8. )
    9. class User:
    10. pass
    11. mapper_registry.map_imperatively(User, user_table)

    The above class, mapped imperatively as described at , will also feature the default constructor associated with the registry.

    New in version 1.4: classical mappings now support a standard configuration-level constructor when they are mapped via the method.

    Runtime Introspection of Mapped classes, Instances and Mappers

    A class that is mapped using will also feature a few attributes that are common to all mappings:

    • The __table__ attribute will refer to the Table, or more generically to the object, to which the class is mapped:

      This FromClause is also what’s returned when using the attribute of the Mapper:

      1. table = inspect(User).local_table

      For a single-table inheritance mapping, where the class is a subclass that does not have a table of its own, the attribute as well as the .__table__ attribute will be None. To retrieve the “selectable” that is actually selected from during a query for this class, this is available via the Mapper.selectable attribute:

      1. table = inspect(User).selectable

    Inspection of Mapper objects

    As illustrated in the previous section, the Mapper object is available from any mapped class, regardless of method, using the system. Using the inspect() function, one can acquire the from a mapped class:

    1. >>> from sqlalchemy import inspect
    2. >>> insp = inspect(User)

    Detailed information is available including Mapper.columns:

    1. >>> insp.columns
    2. <sqlalchemy.util._collections.OrderedProperties object at 0x102f407f8>

    This is a namespace that can be viewed in a list format or via individual names:

    1. >>> list(insp.columns)
    2. [Column('id', Integer(), table=<user>, primary_key=True, nullable=False), Column('name', String(length=50), table=<user>), Column('fullname', String(length=50), table=<user>), Column('nickname', String(length=50), table=<user>)]
    3. >>> insp.columns.name
    4. Column('name', String(length=50), table=<user>)

    Other namespaces include , which includes all mapped attributes as well as hybrids, association proxies:

    1. >>> insp.all_orm_descriptors
    2. <sqlalchemy.util._collections.ImmutableProperties object at 0x1040e2c68>
    3. >>> insp.all_orm_descriptors.keys()
    4. ['fullname', 'nickname', 'name', 'id']

    As well as Mapper.column_attrs:

    1. >>> list(insp.column_attrs)
    2. [<ColumnProperty at 0x10403fde0; id>, <ColumnProperty at 0x10403fce8; name>, <ColumnProperty at 0x1040e9050; fullname>, <ColumnProperty at 0x1040e9148; nickname>]
    3. >>> insp.column_attrs.name
    4. <ColumnProperty at 0x10403fce8; name>
    5. >>> insp.column_attrs.name.expression
    6. Column('name', String(length=50), table=<user>)

    See also

    Inspection of Mapped Instances

    The function also provides information about instances of a mapped class. When applied to an instance of a mapped class, rather than the class itself, the object returned is known as InstanceState, which will provide links to not only the in use by the class, but also a detailed interface that provides information on the state of individual attributes within the instance including their current value and how this relates to what their database-loaded value is.

    Given an instance of the User class loaded from the database:

    The inspect() function will return to us an object:

    1. >>> insp = inspect(u1)
    2. >>> insp
    3. <sqlalchemy.orm.state.InstanceState object at 0x7f07e5fec2e0>

    With this object we can see elements such as the Mapper:

    1. >>> insp.mapper
    2. <Mapper at 0x7f07e614ef50; User>

    The to which the object is attached, if any:

    1. >>> insp.session
    2. <sqlalchemy.orm.session.Session object at 0x7f07e614f160>

    Information about the current for the object:

    1. >>> insp.persistent
    2. True
    3. >>> insp.pending
    4. False

    Attribute state information such as attributes that have not been loaded or lazy loaded (assume addresses refers to a on the mapped class to a related class):

    1. >>> insp.unloaded
    2. {'addresses'}

    Information regarding the current in-Python status of attributes, such as attributes that have not been modified since the last flush:

    1. >>> insp.unmodified
    2. {'nickname', 'name', 'fullname', 'id'}

    as well as specific history on modifications to attributes since the last flush:

    1. >>> insp.attrs.nickname.value
    2. 'nickname'
    3. >>> u1.nickname = "new nickname"

    See also

    InstanceState

    AttributeState

    []

    When running under Python 2, a Python 2 “old style” class is the only kind of class that isn’t compatible. When running code on Python 2, all classes must extend from the Python object class. Under Python 3 this is always the case.

    There is a legacy feature known as a “non primary mapper”, where additional Mapper objects may be associated with a class that’s already mapped, however they don’t apply instrumentation to the class. This feature is deprecated as of SQLAlchemy 1.3.