module documentation

Public API functions and helpers for declarative.
Class registry Generalized registry for mapping classes.
Class ​_stateful​_declared​_attr Undocumented
Function ​_inspect​_decl​_meta Undocumented
Function as​_declarative Class decorator which will adapt a given class into a _orm.declarative_base.
Function declarative​_base Construct a base class for declarative class definitions.
Function declarative​_mixin Mark a class as providing the feature of "declarative mixin".
Function has​_inherited​_table Given a class, return True if any of the classes it inherits from has a mapped table, otherwise return False.
Function synonym​_for Decorator that produces an _orm.synonym attribute in conjunction with a Python descriptor.
@inspection._inspects(DeclarativeMeta)
def _inspect_decl_meta(cls):

Undocumented

@util.deprecated_params(bind=('2.0', 'The ``bind`` argument to as_declarative is deprecated and will be removed in SQLAlchemy 2.0.'))
def as_declarative(**kw):

Class decorator which will adapt a given class into a _orm.declarative_base.

This function makes use of the _orm.registry.as_declarative_base method, by first creating a _orm.registry automatically and then invoking the decorator.

E.g.:

from sqlalchemy.orm 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):
    # ...

See Also

_orm.registry.as_declarative_base

def declarative_base(bind=None, metadata=None, mapper=None, cls=object, name='Base', constructor=_declarative_constructor, class_registry=None, metaclass=DeclarativeMeta):

Construct a base class for declarative class definitions.

The new base class will be given a metaclass that produces appropriate ~sqlalchemy.schema.Table objects and makes the appropriate ~sqlalchemy.orm.mapper calls based on the information provided declaratively in the class and any subclasses of the class.

The _orm.declarative_base function is a shorthand version of using the _orm.registry.generate_base method. That is, the following:

from sqlalchemy.orm import declarative_base

Base = declarative_base()

Is equivalent to:

from sqlalchemy.orm import registry

mapper_registry = registry()
Base = mapper_registry.generate_base()

See the docstring for _orm.registry and _orm.registry.generate_base for more details.

Changed in version 1.4: The _orm.declarative_base function is now a specialization of the more generic _orm.registry class. The function also moves to the sqlalchemy.orm package from the declarative.ext package.

See Also

_orm.registry

Parameters
bind

An optional ~sqlalchemy.engine.Connectable, will be assigned the bind attribute on the ~sqlalchemy.schema.MetaData instance.

Deprecated since version 1.4: The "bind" argument to declarative_base is deprecated and will be removed in SQLAlchemy 2.0.
metadataAn optional ~sqlalchemy.schema.MetaData instance. All ~sqlalchemy.schema.Table objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The ~sqlalchemy.schema.MetaData instance will be available via the metadata attribute of the generated declarative base class.
mapperAn optional callable, defaults to ~sqlalchemy.orm.mapper. Will be used to map subclasses to their Tables.
clsDefaults to object. A type to use as the base for the generated declarative base class. May be a class or tuple of classes.
nameDefaults to Base. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging.
constructorSpecify the implementation for the __init__ function on a mapped class that has no __init__ of its own. Defaults to an implementation that assigns **kwargs for declared fields and relationships to an instance. If None is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics.
class​_registryoptional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of _orm.relationship and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships.
metaclassDefaults to .DeclarativeMeta. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class.
def declarative_mixin(cls):

Mark a class as providing the feature of "declarative mixin".

E.g.:

from sqlalchemy.orm import declared_attr
from sqlalchemy.orm import declarative_mixin

@declarative_mixin
class MyMixin:

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    __table_args__ = {'mysql_engine': 'InnoDB'}
    __mapper_args__= {'always_refresh': True}

    id =  Column(Integer, primary_key=True)

class MyModel(MyMixin, Base):
    name = Column(String(1000))

The _orm.declarative_mixin decorator currently does not modify the given class in any way; it's current purpose is strictly to assist the :ref:`Mypy plugin <mypy_toplevel>` in being able to identify SQLAlchemy declarative mixin classes when no other context is present.

New in version 1.4.6.
def has_inherited_table(cls):

Given a class, return True if any of the classes it inherits from has a mapped table, otherwise return False.

This is used in declarative mixins to build attributes that behave differently for the base class vs. a subclass in an inheritance hierarchy.

def synonym_for(name, map_column=False):

Decorator that produces an _orm.synonym attribute in conjunction with a Python descriptor.

The function being decorated is passed to _orm.synonym as the :paramref:`.orm.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 :ref:`hybrid properties <mapper_hybrids>` feature of SQLAlchemy is typically preferred instead of synonyms, which is a more legacy feature.

See Also

:ref:`synonyms` - Overview of synonyms

_orm.synonym - the mapper-level function

:ref:`mapper_hybrids` - The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than can be achieved with synonyms.