Construct a base class for declarative class definitions.
The new base class will be given a metaclass that produces appropriate Table objects and makes the appropriate mapper() calls based on the information provided declaratively in the class and any subclasses of the class.
Parameters: |
|
---|
See also
as_declarative()
Bases: sqlalchemy.orm.base._MappedAttribute, __builtin__.property
Mark a class-level method as representing the definition of a mapped property or special declarative member name.
@declared_attr turns the attribute into a scalar-like property that can be invoked from the uninstantiated class. Declarative treats attributes specifically marked with @declared_attr as returning a construct that is specific to mapping or declarative table configuration. The name of the attribute is that of what the non-dynamic version of the attribute would be.
@declared_attr is more often than not applicable to mixins, to define relationships that are to be applied to different implementors 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 provide a “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__}
Changed in version 0.8: declared_attr can be used with non-ORM or extension attributes, such as user-defined attributes or association_proxy() objects, which will be assigned to the class at class construction time.
A simple constructor that allows initialization from kwargs.
Sets attributes on the constructed instance using the names and values in kwargs.
Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.
Given a class, return True if any of the classes it inherits from has a mapped table, otherwise return False.
Decorator, make a Python @property a query synonym for a column.
A decorator version of synonym(). The function being decorated is the ‘descriptor’, otherwise passes its arguments through to synonym():
@synonym_for('col')
@property
def prop(self):
return 'special sauce'
The regular synonym() is also usable directly in a declarative setting and may be convenient for read/write properties:
prop = synonym('col', descriptor=property(_read_prop, _write_prop))
Decorator, allow a Python @property to be used in query criteria.
This is a decorator front end to comparable_property() that passes through the comparator_factory and the function being decorated:
@comparable_using(MyComparatorType)
@property
def prop(self):
return 'special sauce'
The regular comparable_property() is also usable directly in a declarative setting and may be convenient for read/write properties:
prop = comparable_property(MyComparatorType)
Given a class, configure the class declaratively, using the given registry, which can be any dictionary, and MetaData 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 subclass to this class. The function is called via the __declare_last__() function, which is essentially a hook for the after_configured() event.
AbstractConcreteBase does not produce a mapped table for the class itself. Compare to ConcreteBase, which does.
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}
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:
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}
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=True 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:
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 of classes have been defined in the above fashion, all tables can be reflected and mappings created using prepare():
engine = create_engine("someengine://...")
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.:
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 and ReflectedTwo can be configured separately:
ReflectedOne.prepare(engine_one)
ReflectedTwo.prepare(engine_two)
New in version 0.8.
Reflect all Table objects for all current DeferredReflection subclasses
The __declare_last__() hook allows definition of a class level function that is automatically called by the MapperEvents.after_configured() event, which occurs after mappings are assumed to be completed and the ‘configure’ step has finished:
class MyClass(Base):
@classmethod
def __declare_last__(cls):
""
# do something with mappings
New in version 0.7.3.
Like __declare_last__(), but is called at the beginning of mapper configuration 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__ causes declarative to skip the production of a table or mapper for the class entirely. A class can be added within a hierarchy in the same way as mixin (see Mixin and Custom Base Classes), allowing subclasses 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 distinct MetaData 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 one MetaData as the registry of tables, and those which inherit from OtherBase will use a different one. The tables themselves can then be created perhaps within distinct databases:
DefaultBase.metadata.create_all(some_engine)
OtherBase.metadata_create_all(some_other_engine)
New in version 0.7.3.