Declarative Extensions

Extensions specific to the Declarative mapping API.

Changed in version 1.4: The vast majority of the Declarative extension is now integrated into the SQLAlchemy ORM and is importable from the sqlalchemy.orm namespace. See the documentation at Declarative Mapping for new documentation. For an overview of the change, see Declarative is now integrated into the ORM with new features.

Object NameDescription

AbstractConcreteBase

A helper class for ‘concrete’ declarative mappings.

ConcreteBase

A helper class for ‘concrete’ declarative mappings.

DeferredReflection

A helper class for construction of mappings based on a deferred reflection step.

class sqlalchemy.ext.declarative.AbstractConcreteBase

A helper class for ‘concrete’ declarative mappings.

AbstractConcreteBase will use the polymorphic_union() function automatically, against all tables mapped as a subclass to this class. The function is called via the __declare_first__() function, which is essentially a hook for the before_configured() event.

AbstractConcreteBase applies Mapper for its immediately inheriting class, as would occur for any other declarative mapped class. However, the Mapper is not mapped to any particular Table object. Instead, it’s mapped directly to the “polymorphic” selectable produced by polymorphic_union(), and performs no persistence operations on its own. Compare to ConcreteBase, which maps its immediately inheriting class to an actual Table that stores rows directly.

Note

The AbstractConcreteBase delays the mapper creation of the base class until all the subclasses have been defined, as it needs to create a mapping against a selectable that will include all subclass tables. In order to achieve this, it waits for the mapper configuration event to occur, at which point it scans through all the configured subclasses and sets up a mapping that will query against all subclasses at once.

While this event is normally invoked automatically, in the case of AbstractConcreteBase, it may be necessary to invoke it explicitly after all subclass mappings are defined, if the first operation is to be a query against this base class. To do so, once all the desired classes have been configured, the registry.configure() method on the registry in use can be invoked, which is available in relation to a particular declarative base class:

  1. Base.registry.configure()

Example:

  1. from sqlalchemy.orm import DeclarativeBase
  2. from sqlalchemy.ext.declarative import AbstractConcreteBase
  3. class Base(DeclarativeBase):
  4. pass
  5. class Employee(AbstractConcreteBase, Base):
  6. pass
  7. class Manager(Employee):
  8. __tablename__ = 'manager'
  9. employee_id = Column(Integer, primary_key=True)
  10. name = Column(String(50))
  11. manager_data = Column(String(40))
  12. __mapper_args__ = {
  13. 'polymorphic_identity':'manager',
  14. 'concrete':True
  15. }
  16. Base.registry.configure()

The abstract base class is handled by declarative in a special way; at class configuration time, it behaves like a declarative mixin or an __abstract__ base class. Once classes are configured and mappings are produced, it then gets mapped itself, but after all of its descendants. This is a very unique system of mapping not found in any other SQLAlchemy API feature.

Using this approach, we can specify columns and properties that will take place on mapped subclasses, in the way that we normally do as in Mixin and Custom Base Classes:

  1. from sqlalchemy.ext.declarative import AbstractConcreteBase
  2. class Company(Base):
  3. __tablename__ = 'company'
  4. id = Column(Integer, primary_key=True)
  5. class Employee(AbstractConcreteBase, Base):
  6. strict_attrs = True
  7. employee_id = Column(Integer, primary_key=True)
  8. @declared_attr
  9. def company_id(cls):
  10. return Column(ForeignKey('company.id'))
  11. @declared_attr
  12. def company(cls):
  13. return relationship("Company")
  14. class Manager(Employee):
  15. __tablename__ = 'manager'
  16. name = Column(String(50))
  17. manager_data = Column(String(40))
  18. __mapper_args__ = {
  19. 'polymorphic_identity':'manager',
  20. 'concrete':True
  21. }
  22. Base.registry.configure()

When we make use of our mappings however, both Manager and Employee will have an independently usable .company attribute:

  1. session.execute(
  2. select(Employee).filter(Employee.company.has(id=5))
  3. )
  • Parameters:

    strict_attrs

    when specified on the base class, “strict” attribute mode is enabled which attempts to limit ORM mapped attributes on the base class to only those that are immediately present, while still preserving “polymorphic” loading behavior.

    New in version 2.0.

See also

ConcreteBase

Concrete Table Inheritance

Abstract Concrete Classes

Class signature

class sqlalchemy.ext.declarative.AbstractConcreteBase (sqlalchemy.ext.declarative.extensions.ConcreteBase)

class sqlalchemy.ext.declarative.ConcreteBase

A helper class for ‘concrete’ declarative mappings.

ConcreteBase will use the polymorphic_union() function automatically, against all tables mapped as a subclass to this class. The function is called via the __declare_last__() function, which is essentially a hook for the after_configured() event.

ConcreteBase produces a mapped table for the class itself. Compare to AbstractConcreteBase, which does not.

Example:

  1. from sqlalchemy.ext.declarative import ConcreteBase
  2. class Employee(ConcreteBase, Base):
  3. __tablename__ = 'employee'
  4. employee_id = Column(Integer, primary_key=True)
  5. name = Column(String(50))
  6. __mapper_args__ = {
  7. 'polymorphic_identity':'employee',
  8. 'concrete':True}
  9. class Manager(Employee):
  10. __tablename__ = 'manager'
  11. employee_id = Column(Integer, primary_key=True)
  12. name = Column(String(50))
  13. manager_data = Column(String(40))
  14. __mapper_args__ = {
  15. 'polymorphic_identity':'manager',
  16. 'concrete':True}

The name of the discriminator column used by polymorphic_union() defaults to the name type. To suit the use case of a mapping where an actual column in a mapped table is already named type, the discriminator name can be configured by setting the _concrete_discriminator_name attribute:

  1. class Employee(ConcreteBase, Base):
  2. _concrete_discriminator_name = '_concrete_discriminator'

New in version 1.3.19: Added the _concrete_discriminator_name attribute to ConcreteBase so that the virtual discriminator column name can be customized.

Changed in version 1.4.2: The _concrete_discriminator_name attribute need only be placed on the basemost class to take correct effect for all subclasses. An explicit error message is now raised if the mapped column names conflict with the discriminator name, whereas in the 1.3.x series there would be some warnings and then a non-useful query would be generated.

See also

AbstractConcreteBase

Concrete Table Inheritance

class sqlalchemy.ext.declarative.DeferredReflection

A helper class for construction of mappings based on a deferred reflection step.

Normally, declarative can be used with reflection by setting a Table object using autoload_with=engine as the __table__ attribute on a declarative class. The caveat is that the Table must be fully reflected, or at the very least have a primary key column, at the point at which a normal declarative mapping is constructed, meaning the Engine must be available at class declaration time.

The DeferredReflection mixin moves the construction of mappers to be at a later point, after a specific method is called which first reflects all Table objects created so far. Classes can define it as such:

  1. from sqlalchemy.ext.declarative import declarative_base
  2. from sqlalchemy.ext.declarative import DeferredReflection
  3. Base = declarative_base()
  4. class MyClass(DeferredReflection, Base):
  5. __tablename__ = 'mytable'

Above, MyClass is not yet mapped. After a series of classes have been defined in the above fashion, all tables can be reflected and mappings created using prepare():

  1. engine = create_engine("someengine://...")
  2. DeferredReflection.prepare(engine)

The DeferredReflection mixin can be applied to individual classes, used as the base for the declarative base itself, or used in a custom abstract class. Using an abstract base allows that only a subset of classes to be prepared for a particular prepare step, which is necessary for applications that use more than one engine. For example, if an application has two engines, you might use two bases, and prepare each separately, e.g.:

  1. class ReflectedOne(DeferredReflection, Base):
  2. __abstract__ = True
  3. class ReflectedTwo(DeferredReflection, Base):
  4. __abstract__ = True
  5. class MyClass(ReflectedOne):
  6. __tablename__ = 'mytable'
  7. class MyOtherClass(ReflectedOne):
  8. __tablename__ = 'myothertable'
  9. class YetAnotherClass(ReflectedTwo):
  10. __tablename__ = 'yetanothertable'
  11. # ... etc.

Above, the class hierarchies for ReflectedOne and ReflectedTwo can be configured separately:

  1. ReflectedOne.prepare(engine_one)
  2. ReflectedTwo.prepare(engine_two)

Members

prepare()

See also

Using DeferredReflection - in the Table Configuration with Declarative section.