Declarative API
API Reference
sqlalchemy.ext.declarative.
declarativebase
(_bind=None, metadata=None, mapper=None, cls=, name='Base', constructor= , class_registry=None, metaclass= ) - Construct a base class for declarative class definitions.
The new base class will be given a metaclass that producesappropriate Table
objects and makesthe appropriate mapper()
calls based on theinformation provided declaratively in the class and any subclassesof the class.
- Parameters
bind – An optional
Connectable
, will be assignedthebind
attribute on theMetaData
instance.metadata – An optional
MetaData
instance. AllTable
objects implicitly declared bysubclasses of the base will share this MetaData. A MetaData instancewill be created if none is provided. TheMetaData
instance will be available via themetadata attribute of the generated declarative base class.mapper – An optional callable, defaults to
mapper()
. Willbe used to map subclasses to their Tables.cls – Defaults to
object
. A type to use as the base for the generateddeclarative base class. May be a class or tuple of classes.name – Defaults to
Base
. The display name for the generatedclass. Customizing this is not required, but can improve clarity intracebacks and debugging.constructor – Defaults to
declarativeconstructor()
, aninit implementation that assigns **kwargs for declaredfields and relationships to an instance. IfNone
is supplied,no init will be provided and construction will fall back tocls.__init by way of the normal Python semantics.class_registry – optional dictionary that will serve as theregistry of class names-> mapped classes when string namesare used to identify classes inside of
relationship()
and others. Allows two or more declarative base classesto share the same registry of class names for simplifiedinter-base relationships.metaclass – Defaults to
DeclarativeMeta
. A metaclass or metaclasscompatible callable to use as the meta type of the generateddeclarative base class.
Changed in version 1.1: if declarative_base.cls
is asingle class (rather than a tuple), the constructed base class willinherit its docstring.
See also
sqlalchemy.ext.declarative.
asdeclarative
(**kw_)- Class decorator for
declarative_base()
.
Provides a syntactical shortcut to the cls
argumentsent to declarative_base()
, allowing the base classto be converted in-place to a “declarative” base:
- from sqlalchemy.ext.declarative import as_declarative
- @as_declarative()
- class Base(object):
- @declared_attr
- def __tablename__(cls):
- return cls.__name__.lower()
- id = Column(Integer, primary_key=True)
- class MyMappedClass(Base):
- # ...
All keyword arguments passed to as_declarative()
are passedalong to declarative_base()
.
See also
- class
sqlalchemy.ext.declarative.
declaredattr
(_fget, cascading=False) - Bases:
sqlalchemy.orm.base._MappedAttribute
,builtins.property
Mark a class-level method as representing the definition ofa mapped property or special declarative member name.
@declared_attr turns the attribute into a scalar-likeproperty that can be invoked from the uninstantiated class.Declarative treats attributes specifically marked with@declared_attr as returning a construct that is specificto mapping or declarative table configuration. The nameof the attribute is that of what the non-dynamic versionof the attribute would be.
@declared_attr is more often than not applicable to mixins,to define relationships that are to be applied to differentimplementors of the class:
- class ProvidesUser(object):
- "A mixin that adds a 'user' relationship to classes."
- @declared_attr
- def user(self):
- return relationship("User")
It also can be applied to mapped classes, such as to providea “polymorphic” scheme for inheritance:
- class Employee(Base):
- id = Column(Integer, primary_key=True)
- type = Column(String(50), nullable=False)
- @declared_attr
- def __tablename__(cls):
- return cls.__name__.lower()
- @declared_attr
- def __mapper_args__(cls):
- if cls.__name__ == 'Employee':
- return {
- "polymorphic_on":cls.type,
- "polymorphic_identity":"Employee"
- }
- else:
- return {"polymorphic_identity":cls.__name__}
- property
cascading
- Mark a
declared_attr
as cascading.
This is a special-use modifier which indicates that a columnor MapperProperty-based declared attribute should be configureddistinctly per mapped subclass, within a mapped-inheritance scenario.
Warning
The declared_attr.cascading
modifier has severallimitations:
-
The flag only applies to the use of declared_attr
on declarative mixin classes and abstract
classes; itcurrently 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 downthe class hierarchy; if a subclass tries to override theattribute, a warning is emitted and the overridden attributeis skipped. This is a limitation that it is hoped will beresolved at some point.
Below, both MyClass as well as MySubClass will have a distinctid
Column object established:
- class HasIdMixin(object):
- @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 ofMyClass
underneath the attribute named some_id
.
See also
Mixing in Columns in Inheritance Scenarios
sqlalchemy.ext.declarative.api.
declarative_constructor
(_self, **kwargs)- A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names andvalues in kwargs
.
Only keys that are present asattributes of the instance’s class are allowed. These could be,for example, any mapped columns or relationships.
sqlalchemy.ext.declarative.
hasinherited_table
(_cls)- Given a class, return True if any of the classes it inherits from has amapped table, otherwise return False.
This is used in declarative mixins to build attributes that behavedifferently for the base class vs. a subclass in an inheritancehierarchy.
See also
Controlling table inheritance with mixins
sqlalchemy.ext.declarative.
synonymfor
(_name, map_column=False)- Decorator that produces an
orm.synonym()
attribute in conjunctionwith a Python descriptor.
The function being decorated is passed to orm.synonym()
as theorm.synonym.descriptor
parameter:
- class MyClass(Base):
- __tablename__ = 'my_table'
- id = Column(Integer, primary_key=True)
- _job_status = Column("job_status", String(50))
- @synonym_for("job_status")
- @property
- def job_status(self):
- return "Status: %s" % self._job_status
The hybrid properties feature of SQLAlchemyis typically preferred instead of synonyms, which is a more legacyfeature.
See also
Synonyms - Overview of synonyms
orm.synonym()
- the mapper-level function
Using Descriptors and Hybrids - The Hybrid Attribute extension provides anupdated approach to augmenting attribute behavior more flexibly thancan be achieved with synonyms.
sqlalchemy.ext.declarative.
comparableusing
(_comparator_factory)- Decorator, allow a Python @property to be used in query criteria.
This is a decorator front end tocomparable_property()
that passesthrough the comparator_factory and the function being decorated:
- @comparable_using(MyComparatorType)@propertydef prop(self): return 'special sauce'
The regular comparable_property()
is also usable directly in adeclarative setting and may be convenient for read/write properties:
- prop = comparable_property(MyComparatorType)
sqlalchemy.ext.declarative.
instrumentdeclarative
(_cls, registry, metadata)Given a class, configure the class declaratively,using the given registry, which can be any dictionary, andMetaData object.
- Bases:
sqlalchemy.ext.declarative.api.ConcreteBase
A helper class for ‘concrete’ declarative mappings.
AbstractConcreteBase
will use the polymorphic_union()
function automatically, against all tables mapped as a subclassto this class. The function is called via thedeclare_last()
function, which is essentiallya hook for the after_configured()
event.
AbstractConcreteBase
does produce a mapped classfor the base class, however it is not persisted to any table; itis instead mapped directly to the “polymorphic” selectable directlyand is only used for selecting. Compare to ConcreteBase
,which does create a persisted table for the base class.
Note
The AbstractConcreteBase
class does not intend to set up themapping for the base class until all the subclasses have been defined,as it needs to create a mapping against a selectable that will includeall subclass tables. In order to achieve this, it waits for themapper configuration event to occur, at which point it scansthrough all the configured subclasses and sets up a mapping that willquery against all subclasses at once.
While this event is normally invoked automatically, in the case ofAbstractConcreteBase
, it may be necessary to invoke itexplicitly after all subclass mappings are defined, if the firstoperation is to be a query against this base class. To do so, invokeconfigure_mappers()
once all the desired classes have beenconfigured:
- from sqlalchemy.orm import configure_mappers
- configure_mappers()
See also
Example:
- from sqlalchemy.ext.declarative import AbstractConcreteBase
- class Employee(AbstractConcreteBase, Base):
- pass
- class Manager(Employee):
- __tablename__ = 'manager'
- employee_id = Column(Integer, primary_key=True)
- name = Column(String(50))
- manager_data = Column(String(40))
- __mapper_args__ = {
- 'polymorphic_identity':'manager',
- 'concrete':True}
- configure_mappers()
The abstract base class is handled by declarative in a special way;at class configuration time, it behaves like a declarative mixinor an abstract
base class. Once classes are configuredand mappings are produced, it then gets mapped itself, butafter all of its descendants. This is a very unique system of mappingnot found in any other SQLAlchemy system.
Using this approach, we can specify columns and propertiesthat will take place on mapped subclasses, in the way thatwe normally do as in Mixin and Custom Base Classes:
- class Company(Base):
- __tablename__ = 'company'
- id = Column(Integer, primary_key=True)
- class Employee(AbstractConcreteBase, Base):
- employee_id = Column(Integer, primary_key=True)
- @declared_attr
- def company_id(cls):
- return Column(ForeignKey('company.id'))
- @declared_attr
- def company(cls):
- return relationship("Company")
- class Manager(Employee):
- __tablename__ = 'manager'
- name = Column(String(50))
- manager_data = Column(String(40))
- __mapper_args__ = {
- 'polymorphic_identity':'manager',
- 'concrete':True}
- configure_mappers()
When we make use of our mappings however, both Manager
andEmployee
will have an independently usable .company
attribute:
- session.query(Employee).filter(Employee.company.has(id=5))
Changed in version 1.0.0: - The mechanics of AbstractConcreteBase
have been reworked to support relationships established directlyon the abstract base, without any special configurational steps.
See also
inheritance_concrete_helpers
ConcreteBase
will use the polymorphic_union()
function automatically, against all tables mapped as a subclassto this class. The function is called via thedeclare_last()
function, which is essentiallya hook for the after_configured()
event.
ConcreteBase
produces a mappedtable for the class itself. Compare to AbstractConcreteBase
,which does not.
Example:
- from sqlalchemy.ext.declarative import ConcreteBase
- class Employee(ConcreteBase, Base):
- __tablename__ = 'employee'
- employee_id = Column(Integer, primary_key=True)
- name = Column(String(50))
- __mapper_args__ = {
- 'polymorphic_identity':'employee',
- 'concrete':True}
- class Manager(Employee):
- __tablename__ = 'manager'
- employee_id = Column(Integer, primary_key=True)
- name = Column(String(50))
- manager_data = Column(String(40))
- __mapper_args__ = {
- 'polymorphic_identity':'manager',
- 'concrete':True}
See also
inheritance_concrete_helpers
- class
sqlalchemy.ext.declarative.
DeferredReflection
- A helper class for construction of mappings based ona deferred reflection step.
Normally, declarative can be used with reflection bysetting a Table
object using autoload=Trueas the table
attribute on a declarative class.The caveat is that the Table
must be fullyreflected, or at the very least have a primary key column,at the point at which a normal declarative mapping isconstructed, meaning the Engine
must be availableat class declaration time.
The DeferredReflection
mixin moves the constructionof mappers to be at a later point, after a specificmethod is called which first reflects all Table
objects created so far. Classes can define it as such:
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.ext.declarative import DeferredReflection
- Base = declarative_base()
- class MyClass(DeferredReflection, Base):
- __tablename__ = 'mytable'
Above, MyClass
is not yet mapped. After a series ofclasses have been defined in the above fashion, all tablescan be reflected and mappings created usingprepare()
:
- engine = create_engine("someengine://...")
- DeferredReflection.prepare(engine)
The DeferredReflection
mixin can be applied to individualclasses, used as the base for the declarative base itself,or used in a custom abstract class. Using an abstract baseallows that only a subset of classes to be prepared for aparticular prepare step, which is necessary for applicationsthat use more than one engine. For example, if an applicationhas two engines, you might use two bases, and prepare eachseparately, e.g.:
- class ReflectedOne(DeferredReflection, Base):
- __abstract__ = True
- class ReflectedTwo(DeferredReflection, Base):
- __abstract__ = True
- class MyClass(ReflectedOne):
- __tablename__ = 'mytable'
- class MyOtherClass(ReflectedOne):
- __tablename__ = 'myothertable'
- class YetAnotherClass(ReflectedTwo):
- __tablename__ = 'yetanothertable'
- # ... etc.
Above, the class hierarchies for ReflectedOne
andReflectedTwo
can be configured separately:
- ReflectedOne.prepare(engine_one)
- ReflectedTwo.prepare(engine_two)
- classmethod
prepare
(engine) - Reflect all
Table
objects for all currentDeferredReflection
subclasses
Special Directives
declare_last()
The declare_last()
hook allows definition ofa class level function that is automatically called by theMapperEvents.after_configured()
event, which occurs after mappings areassumed to be completed and the ‘configure’ step has finished:
- class MyClass(Base):
- @classmethod
- def __declare_last__(cls):
- ""
- # do something with mappings
declare_first()
Like declare_last()
, but is called at the beginning of mapperconfiguration via the MapperEvents.before_configured()
event:
- class MyClass(Base):
- @classmethod
- def __declare_first__(cls):
- ""
- # do something before mappings are configured
New in version 0.9.3.
abstract
abstract
causes declarative to skip the productionof a table or mapper for the class entirely. A class can be added within ahierarchy in the same way as mixin (see Mixin and Custom Base Classes), allowingsubclasses to extend just from the special class:
- class SomeAbstractBase(Base):
- __abstract__ = True
- def some_helpful_method(self):
- ""
- @declared_attr
- def __mapper_args__(cls):
- return {"helpful mapper arguments":True}
- class MyMappedClass(SomeAbstractBase):
- ""
One possible use of abstract
is to use a distinctMetaData
for different bases:
- Base = declarative_base()
- class DefaultBase(Base):
- __abstract__ = True
- metadata = MetaData()
- class OtherBase(Base):
- __abstract__ = True
- metadata = MetaData()
Above, classes which inherit from DefaultBase
will use oneMetaData
as the registry of tables, and those which inherit fromOtherBase
will use a different one. The tables themselves can then becreated perhaps within distinct databases:
- DefaultBase.metadata.create_all(some_engine)
- OtherBase.metadata_create_all(some_other_engine)
table_cls
Allows the callable / class used to generate a Table
to be customized.This is a very open-ended hook that can allow special customizationsto a Table
that one generates here:
- class MyMixin(object):
- @classmethod
- def __table_cls__(cls, name, metadata, *arg, **kw):
- return Table(
- "my_" + name,
- metadata, *arg, **kw
- )
The above mixin would cause all Table
objects generated to includethe prefix "my"
, followed by the name normally specified using the_tablename
attribute.
table_cls
also supports the case of returning None
, whichcauses the class to be considered as single-table inheritance vs. its subclass.This may be useful in some customization schemes to determine that single-tableinheritance should take place based on the arguments for the table itself,such as, define as single-inheritance if there is no primary key present:
- class AutoTable(object):
- @declared_attr
- def __tablename__(cls):
- return cls.__name__
- @classmethod
- def __table_cls__(cls, *arg, **kw):
- for obj in arg[1:]:
- if (isinstance(obj, Column) and obj.primary_key) or \
- isinstance(obj, PrimaryKeyConstraint):
- return Table(*arg, **kw)
- return None
- class Person(AutoTable, Base):
- id = Column(Integer, primary_key=True)
- class Employee(Person):
- employee_name = Column(String)
The above Employee
class would be mapped as single-table inheritanceagainst Person
; the employee_name
column would be added as a memberof the Person
table.
New in version 1.0.0.