Declarative Mapping Styles

As introduced at Declarative Mapping, the Declarative Mapping is the typical way that mappings are constructed in modern SQLAlchemy. This section will provide an overview of forms that may be used for Declarative mapper configuration.

Using a Declarative Base Class

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

  1. from sqlalchemy.orm import DeclarativeBase
  2. # declarative base class
  3. class Base(DeclarativeBase):
  4. pass

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

  1. from sqlalchemy.orm import DeclarativeBase
  2. from sqlalchemy.orm import registry
  3. reg = registry()
  4. # declarative base class
  5. class Base(DeclarativeBase):
  6. registry = reg

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

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

  1. from datetime import datetime
  2. from typing import Optional
  3. from sqlalchemy import ForeignKey
  4. from sqlalchemy import func
  5. from sqlalchemy import Integer
  6. from sqlalchemy import String
  7. from sqlalchemy.orm import DeclarativeBase
  8. from sqlalchemy.orm import Mapped
  9. from sqlalchemy.orm import mapped_column
  10. from sqlalchemy.orm import relationship
  11. class Base(DeclarativeBase):
  12. pass
  13. class User(Base):
  14. __tablename__ = "user"
  15. id = mapped_column(Integer, primary_key=True)
  16. name: Mapped[str]
  17. fullname: Mapped[Optional[str]]
  18. nickname: Mapped[Optional[str]] = mapped_column(String(64))
  19. create_date: Mapped[datetime] = mapped_column(insert_default=func.now())
  20. addresses: Mapped[list["Address"]] = relationship(back_populates="user")
  21. class Address(Base):
  22. __tablename__ = "address"
  23. id = mapped_column(Integer, primary_key=True)
  24. user_id = mapped_column(ForeignKey("user.id"))
  25. email_address: Mapped[str]
  26. user: Mapped["User"] = relationship(back_populates="addresses")

Above, the Base class serves as a base for new classes that are to be mapped, as above new mapped classes User and Address are constructed.

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

See also

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

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

Declarative Mapping using a Decorator (no declarative base)

As an alternative to using the “declarative base” class is to apply declarative mapping to a class explicitly, using either an imperative technique similar to that of a “classical” mapping, or more succinctly by using a decorator. The registry.mapped() function is a class decorator that can be applied to any Python class with no hierarchy in place. The Python class otherwise is configured in declarative style normally.

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

  1. from datetime import datetime
  2. from typing import Optional
  3. from sqlalchemy import ForeignKey
  4. from sqlalchemy import func
  5. from sqlalchemy import Integer
  6. from sqlalchemy import String
  7. from sqlalchemy.orm import Mapped
  8. from sqlalchemy.orm import mapped_column
  9. from sqlalchemy.orm import registry
  10. from sqlalchemy.orm import relationship
  11. mapper_registry = registry()
  12. @mapper_registry.mapped
  13. class User:
  14. __tablename__ = "user"
  15. id = mapped_column(Integer, primary_key=True)
  16. name: Mapped[str]
  17. fullname: Mapped[Optional[str]]
  18. nickname: Mapped[Optional[str]] = mapped_column(String(64))
  19. create_date: Mapped[datetime] = mapped_column(insert_default=func.now())
  20. addresses: Mapped[list["Address"]] = relationship(back_populates="user")
  21. @mapper_registry.mapped
  22. class Address:
  23. __tablename__ = "address"
  24. id = mapped_column(Integer, primary_key=True)
  25. user_id = mapped_column(ForeignKey("user.id"))
  26. email_address: Mapped[str]
  27. user: Mapped["User"] = relationship(back_populates="addresses")

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:

  1. from sqlalchemy.orm import registry
  2. mapper_registry = registry()
  3. @mapper_registry.mapped
  4. class Person:
  5. __tablename__ = "person"
  6. person_id = mapped_column(Integer, primary_key=True)
  7. type = mapped_column(String, nullable=False)
  8. __mapper_args__ = {
  9. "polymorphic_on": type,
  10. "polymorphic_identity": "person",
  11. }
  12. @mapper_registry.mapped
  13. class Employee(Person):
  14. __tablename__ = "employee"
  15. person_id = mapped_column(ForeignKey("person.person_id"), primary_key=True)
  16. __mapper_args__ = {
  17. "polymorphic_identity": "employee",
  18. }

Both the declarative table 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 dataclasses and attrs, though note that SQLAlchemy 2.0 now features dataclasses integration with Declarative Base classes as well.