Declarative Mapping Styles

    The most common approach is to generate a “Declarative Base” class by subclassing the superclass:

    The Declarative Base class may also be created given an existing registry by assigning it as a class variable named :

    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.

    With the declarative base class, new mapped classes are declared as subclasses of the base:

    For each subclass constructed, the body of the class then follows the declarative mapping approach which defines both a Table as well as a object behind the scenes which comprise a full mapping.

    See also

    Table Configuration with Declarative - describes how to specify the components of the mapped to be generated, including notes and options on the use of the mapped_column() construct and how it interacts with the annotation type

    Mapper Configuration with Declarative - describes all other aspects of ORM mapper configuration within Declarative including configuration, SQL expressions and Mapper parameters

    Declarative Mapping using a Decorator (no declarative base)

    The example below sets up the identical mapping as seen in the previous section, using the registry.mapped() decorator rather than using the superclass:

    When using the above style, the mapping of a particular class will only proceed if the decorator is applied to that class directly. For inheritance mappings (described in detail at Mapping Class Inheritance Hierarchies), the decorator should be applied to each subclass that is to be mapped:

    Both the and imperative table table configuration styles may be used with either the Declarative Base or decorator styles of Declarative mapping.

    The decorator form of mapping is useful when combining a SQLAlchemy declarative mapping with other class instrumentation systems such as and attrs, though note that SQLAlchemy 2.0 now features dataclasses integration with Declarative Base classes as well.