module documentation

Public API functions and helpers for declarative.

Class DCTransformDeclarative metaclass that includes @dataclass_transforms
Class DeclarativeAttributeIntercept Metaclass that may be used in conjunction with the :class:`_orm.DeclarativeBase` class to support addition of class attributes dynamically.
Class DeclarativeBase Base class used for declarative class definitions.
Class DeclarativeBaseNoMeta Same as :class:`_orm.DeclarativeBase`, but does not use a metaclass to intercept new attributes.
Class MappedAsDataclass Mixin class to indicate when mapping this class, also convert it to be a dataclass.
Class registry Generalized registry for mapping classes.
Function add_mapped_attribute Add a new mapped attribute to an ORM mapped class.
Function as_declarative Class decorator which will adapt a given class into a :func:`_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 :func:`_orm.synonym` attribute in conjunction with a Python descriptor.
Class _declared_attr_common Undocumented
Class _declared_directive Undocumented
Class _DynamicAttributesType Undocumented
Class _stateful_declared_attr Undocumented
Function _check_not_declarative Undocumented
Function _inspect_decl_meta Undocumented
Function _setup_declarative_base Undocumented
Type Variable _T Undocumented
Type Variable _TT Undocumented
Type Alias _DeclaredAttrDecorated Undocumented
Type Alias _MutableTypeAnnotationMapType Undocumented
Type Alias _TypeAnnotationMapType Undocumented
def add_mapped_attribute(target: Type[_O], key: str, attr: MapperProperty[Any]): (source)

Add a new mapped attribute to an ORM mapped class. E.g.:: add_mapped_attribute(User, "addresses", relationship(Address)) This may be used for ORM mappings that aren't using a declarative metaclass that intercepts attribute set operations. .. versionadded:: 2.0

def as_declarative(**kw: Any) -> Callable[[Type[_T]], Type[_T]]: (source)

Class decorator which will adapt a given class into a :func:`_orm.declarative_base`. This function makes use of the :meth:`_orm.registry.as_declarative_base` method, by first creating a :class:`_orm.registry` automatically and then invoking the decorator. E.g.:: from sqlalchemy.orm import as_declarative @as_declarative() class Base: @declared_attr def __tablename__(cls): return cls.__name__.lower() id = Column(Integer, primary_key=True) class MyMappedClass(Base): # ... .. seealso:: :meth:`_orm.registry.as_declarative_base`

def declarative_base(*, metadata: Optional[MetaData] = None, mapper: Optional[Callable[..., Mapper[Any]]] = None, cls: Type[Any] = object, name: str = 'Base', class_registry: Optional[clsregistry._ClsRegistryType] = None, type_annotation_map: Optional[_TypeAnnotationMapType] = None, constructor: Callable[..., None] = _declarative_constructor, metaclass: Type[Any] = DeclarativeMeta) -> Any: (source)

Construct a base class for declarative class definitions. The new base class will be given a metaclass that produces appropriate :class:`~sqlalchemy.schema.Table` objects and makes the appropriate :class:`_orm.Mapper` calls based on the information provided declaratively in the class and any subclasses of the class. .. versionchanged:: 2.0 Note that the :func:`_orm.declarative_base` function is superseded by the new :class:`_orm.DeclarativeBase` class, which generates a new "base" class using subclassing, rather than return value of a function. This allows an approach that is compatible with :pep:`484` typing tools. The :func:`_orm.declarative_base` function is a shorthand version of using the :meth:`_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 :class:`_orm.registry` and :meth:`_orm.registry.generate_base` for more details. .. versionchanged:: 1.4 The :func:`_orm.declarative_base` function is now a specialization of the more generic :class:`_orm.registry` class. The function also moves to the ``sqlalchemy.orm`` package from the ``declarative.ext`` package. :param metadata: An optional :class:`~sqlalchemy.schema.MetaData` instance. All :class:`~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 :class:`~sqlalchemy.schema.MetaData` instance will be available via the ``metadata`` attribute of the generated declarative base class. :param mapper: An optional callable, defaults to :class:`_orm.Mapper`. Will be used to map subclasses to their Tables. :param cls: Defaults to :class:`object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. :param name: Defaults to ``Base``. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. :param constructor: Specify 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. :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of :func:`_orm.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. :param type_annotation_map: optional dictionary of Python types to SQLAlchemy :class:`_types.TypeEngine` classes or instances. This is used exclusively by the :class:`_orm.MappedColumn` construct to produce column types based on annotations within the :class:`_orm.Mapped` type. .. versionadded:: 2.0 .. seealso:: :ref:`orm_declarative_mapped_column_type_map` :param metaclass: Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. .. seealso:: :class:`_orm.registry`

def declarative_mixin(cls: Type[_T]) -> Type[_T]: (source)

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 :func:`_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. .. versionadded:: 1.4.6 .. seealso:: :ref:`orm_mixins_toplevel` :ref:`mypy_declarative_mixins` - in the :ref:`Mypy plugin documentation <mypy_toplevel>`

def has_inherited_table(cls: Type[_O]) -> bool: (source)

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. .. seealso:: :ref:`decl_mixin_inheritance`

def synonym_for(name: str, map_column: bool = False) -> Callable[[Callable[..., Any]], Synonym[Any]]: (source)

Decorator that produces an :func:`_orm.synonym` attribute in conjunction with a Python descriptor. The function being decorated is passed to :func:`_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. .. seealso:: :ref:`synonyms` - Overview of synonyms :func:`_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.

def _check_not_declarative(cls: Type[Any], base: Type[Any]): (source)

Undocumented

def _setup_declarative_base(cls: Type[Any]): (source)

Undocumented

Undocumented

Value
TypeVar('_T',
        bound=Any)

Undocumented

Value
TypeVar('_TT',
        bound=Any)
_DeclaredAttrDecorated = (source)

Undocumented

Value
Callable[..., Union[Mapped[_T], SQLCoreOperations[_T]]]
_MutableTypeAnnotationMapType = (source)

Undocumented

Value
Dict[Any, '_TypeEngineArgument[Any]']
_TypeAnnotationMapType = (source)

Undocumented

Value
Mapping[Any, '_TypeEngineArgument[Any]']