Skip to content

ORM

plateforme.core.database.orm

This module provides utilities for managing database object-relational mapping (ORM) capabilities within the Plateforme framework using SQLAlchemy features.

CascadeRule module-attribute

CascadeRule = Literal[
    "all",
    "delete",
    "delete-orphan",
    "expunge",
    "merge",
    "refresh-expire",
    "save-update",
]

A type alias for the cascade rules that can be used in relationships. The 'all' option indicates a shorthand that is equivalent to the following 'save-update, merge, refresh-expire, expunge, delete'.

LoadRule module-attribute

LoadRule = Literal[
    "joined",
    "noload",
    "select",
    "selectin",
    "raise",
    "raise_on_sql",
    "write_only",
]

A type alias for the load rules that can be used in relationships.

AsyncAttrs

Mixin class which provides an awaitable accessor for all attributes.

E.g.::

from __future__ import annotations

from typing import List

from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship


class Base(AsyncAttrs, DeclarativeBase):
    pass


class A(Base):
    __tablename__ = "a"

    id: Mapped[int] = mapped_column(primary_key=True)
    data: Mapped[str]
    bs: Mapped[List[B]] = relationship()


class B(Base):
    __tablename__ = "b"
    id: Mapped[int] = mapped_column(primary_key=True)
    a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
    data: Mapped[str]

In the above example, the :class:_asyncio.AsyncAttrs mixin is applied to the declarative Base class where it takes effect for all subclasses. This mixin adds a single new attribute :attr:_asyncio.AsyncAttrs.awaitable_attrs to all classes, which will yield the value of any attribute as an awaitable. This allows attributes which may be subject to lazy loading or deferred / unexpiry loading to be accessed such that IO can still be emitted::

a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()

# use the lazy loader on ``a1.bs`` via the ``.awaitable_attrs``
# interface, so that it may be awaited
for b1 in await a1.awaitable_attrs.bs:
    print(b1)

The :attr:_asyncio.AsyncAttrs.awaitable_attrs performs a call against the attribute that is approximately equivalent to using the :meth:_asyncio.AsyncSession.run_sync method, e.g.::

for b1 in await async_session.run_sync(lambda sess: a1.bs):
    print(b1)

.. versionadded:: 2.0.13

.. seealso::

:ref:`asyncio_orm_avoid_lazyloads`

awaitable_attrs property

awaitable_attrs: _AsyncAttrGetitem

provide a namespace of all attributes on this object wrapped as awaitables.

e.g.::

a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()

some_attribute = await a1.awaitable_attrs.some_deferred_attribute
some_collection = await a1.awaitable_attrs.some_collection

ClassManager

ClassManager(class_)

Bases: HasMemoized, Dict[str, 'QueryableAttribute[Any]'], Generic[_O], EventTarget

Tracks state information at the class level.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
def __init__(self, class_):
    self.class_ = class_
    self.info = {}
    self.new_init = None
    self.local_attrs = {}
    self.originals = {}
    self._finalized = False
    self.factory = None
    self.init_method = None

    self._bases = [
        mgr
        for mgr in cast(
            "List[Optional[ClassManager[Any]]]",
            [
                opt_manager_of_class(base)
                for base in self.class_.__bases__
                if isinstance(base, type)
            ],
        )
        if mgr is not None
    ]

    for base_ in self._bases:
        self.update(base_)

    cast(
        "InstanceEvents", self.dispatch._events
    )._new_classmanager_instance(class_, self)

    for basecls in class_.__mro__:
        mgr = opt_manager_of_class(basecls)
        if mgr is not None:
            self.dispatch._update(mgr.dispatch)

    self.manage()

    if "__del__" in class_.__dict__:
        util.warn(
            "__del__() method on class %s will "
            "cause unreachable cycles and memory leaks, "
            "as SQLAlchemy instrumentation often creates "
            "reference cycles.  Please remove this method." % class_
        )

expired_attribute_loader instance-attribute

expired_attribute_loader: _ExpiredAttributeLoaderProto

previously known as deferred_scalar_loader

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

Bases: memoized_property[_T]

A read-only @property that is only evaluated once.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

manage

manage()

Mark this instance as the manager for its class.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
def manage(self):
    """Mark this instance as the manager for its class."""

    setattr(self.class_, self.MANAGER_ATTR, self)

state_getter

state_getter()

Return a (instance) -> InstanceState callable.

"state getter" callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
@util.hybridmethod
def state_getter(self):
    """Return a (instance) -> InstanceState callable.

    "state getter" callables should raise either KeyError or
    AttributeError if no InstanceState could be found for the
    instance.
    """

    return _default_state_getter

unregister

unregister() -> None

remove all instrumentation established by this ClassManager.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
def unregister(self) -> None:
    """remove all instrumentation established by this ClassManager."""

    for key in list(self.originals):
        self.uninstall_member(key)

    self.mapper = None
    self.dispatch = None  # type: ignore
    self.new_init = None
    self.info.clear()

    for key in list(self):
        if key in self.local_attrs:
            self.uninstrument_attribute(key)

    if self.MANAGER_ATTR in self.class_.__dict__:
        delattr(self.class_, self.MANAGER_ATTR)

has_parent

has_parent(
    state: InstanceState[_O],
    key: str,
    optimistic: bool = False,
) -> bool

TODO

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
def has_parent(
    self, state: InstanceState[_O], key: str, optimistic: bool = False
) -> bool:
    """TODO"""
    return self.get_impl(key).hasparent(state, optimistic=optimistic)

ColumnProperty

ColumnProperty(
    column: _ORMColumnExprArgument[_T],
    *additional_columns: _ORMColumnExprArgument[Any],
    attribute_options: Optional[_AttributeOptions] = None,
    group: Optional[str] = None,
    deferred: bool = False,
    raiseload: bool = False,
    comparator_factory: Optional[
        Type[PropComparator[_T]]
    ] = None,
    active_history: bool = False,
    expire_on_flush: bool = True,
    info: Optional[_InfoType] = None,
    doc: Optional[str] = None,
    _instrument: bool = True,
    _assume_readonly_dc_attributes: bool = False,
)

Bases: _MapsColumns[_T], StrategizedProperty[_T], _IntrospectsAnnotations, Identified

Describes an object attribute that corresponds to a table column or other column expression.

Public constructor is the :func:_orm.column_property function.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/properties.py
def __init__(
    self,
    column: _ORMColumnExprArgument[_T],
    *additional_columns: _ORMColumnExprArgument[Any],
    attribute_options: Optional[_AttributeOptions] = None,
    group: Optional[str] = None,
    deferred: bool = False,
    raiseload: bool = False,
    comparator_factory: Optional[Type[PropComparator[_T]]] = None,
    active_history: bool = False,
    expire_on_flush: bool = True,
    info: Optional[_InfoType] = None,
    doc: Optional[str] = None,
    _instrument: bool = True,
    _assume_readonly_dc_attributes: bool = False,
):
    super().__init__(
        attribute_options=attribute_options,
        _assume_readonly_dc_attributes=_assume_readonly_dc_attributes,
    )
    columns = (column,) + additional_columns
    self.columns = [
        coercions.expect(roles.LabeledColumnExprRole, c) for c in columns
    ]
    self.group = group
    self.deferred = deferred
    self.raiseload = raiseload
    self.instrument = _instrument
    self.comparator_factory = (
        comparator_factory
        if comparator_factory is not None
        else self.__class__.Comparator
    )
    self.active_history = active_history
    self.expire_on_flush = expire_on_flush

    if info is not None:
        self.info.update(info)

    if doc is not None:
        self.doc = doc
    else:
        for col in reversed(self.columns):
            doc = getattr(col, "doc", None)
            if doc is not None:
                self.doc = doc
                break
        else:
            self.doc = None

    util.set_creation_order(self)

    self.strategy_key = (
        ("deferred", self.deferred),
        ("instrument", self.instrument),
    )
    if self.raiseload:
        self.strategy_key += (("raiseload", True),)

is_selectable class-attribute instance-attribute

is_selectable = False

Return True if this object is an instance of :class:_expression.Selectable.

is_aliased_class class-attribute instance-attribute

is_aliased_class = False

True if this object is an instance of :class:.AliasedClass.

is_instance class-attribute instance-attribute

is_instance = False

True if this object is an instance of :class:.InstanceState.

is_mapper class-attribute instance-attribute

is_mapper = False

True if this object is an instance of :class:_orm.Mapper.

is_bundle class-attribute instance-attribute

is_bundle = False

True if this object is an instance of :class:.Bundle.

is_property class-attribute instance-attribute

is_property = True

Part of the InspectionAttr interface; states this object is a mapper property.

is_attribute class-attribute instance-attribute

is_attribute = False

True if this object is a Python :term:descriptor.

This can refer to one of many types. Usually a :class:.QueryableAttribute which handles attributes events on behalf of a :class:.MapperProperty. But can also be an extension type such as :class:.AssociationProxy or :class:.hybrid_property. The :attr:.InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

.. seealso::

:attr:`_orm.Mapper.all_orm_descriptors`

is_clause_element class-attribute instance-attribute

is_clause_element = False

True if this object is an instance of :class:_expression.ClauseElement.

extension_type class-attribute instance-attribute

extension_type: InspectionAttrExtensionType = NOT_EXTENSION

The extension type, if any. Defaults to :attr:.interfaces.NotExtension.NOT_EXTENSION

.. seealso::

:class:`.HybridExtensionType`

:class:`.AssociationProxyExtensionType`

info instance-attribute

info: _InfoType

Info dictionary associated with the object, allowing user-defined data to be associated with this :class:.InspectionAttr.

The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:.column_property, :func:_orm.relationship, or :func:.composite functions.

.. seealso::

:attr:`.QueryableAttribute.info`

:attr:`.SchemaItem.info`

comparator instance-attribute

comparator: PropComparator[_T]

The :class:_orm.PropComparator instance that implements SQL expression construction on behalf of this mapped attribute.

key instance-attribute

key: str

name of class attribute

parent instance-attribute

parent: Mapper[Any]

the :class:.Mapper managing this property.

class_attribute property

class_attribute: InstrumentedAttribute[_T]

Return the class-bound descriptor corresponding to this :class:.MapperProperty.

This is basically a getattr() call::

return getattr(self.parent.class_, self.key)

I.e. if this :class:.MapperProperty were named addresses, and the class to which it is mapped is User, this sequence is possible::

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
>>> addresses_property = mapper.attrs.addresses
>>> addresses_property.class_attribute is User.addresses
True
>>> User.addresses.property is addresses_property
True

inherit_cache class-attribute instance-attribute

inherit_cache = True

:meta private:

expression property

expression: ColumnsClauseRole

Return the primary column or expression for this ColumnProperty.

E.g.::

class File(Base):
    # ...

    name = Column(String(64))
    extension = Column(String(8))
    filename = column_property(name + '.' + extension)
    path = column_property('C:/' + filename.expression)

.. seealso::

:ref:`mapper_column_property_sql_expressions_composed`

Comparator

Comparator(
    prop: MapperProperty[_T],
    parentmapper: _InternalEntityType[Any],
    adapt_to_entity: Optional[AliasedInsp[Any]] = None,
)

Bases: MemoizedSlots, PropComparator[_PT]

Produce boolean, comparison, and other operators for :class:.ColumnProperty attributes.

See the documentation for :class:.PropComparator for a brief overview.

.. seealso::

:class:`.PropComparator`

:class:`.ColumnOperators`

:ref:`types_operators`

:attr:`.TypeEngine.comparator_factory`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def __init__(
    self,
    prop: MapperProperty[_T],
    parentmapper: _InternalEntityType[Any],
    adapt_to_entity: Optional[AliasedInsp[Any]] = None,
):
    self.prop = prop
    self._parententity = adapt_to_entity or parentmapper
    self._adapt_to_entity = adapt_to_entity
timetuple class-attribute instance-attribute
timetuple: Literal[None] = None

Hack, allows datetime objects to be compared on the LHS.

expressions instance-attribute
expressions: Sequence[NamedColumn[Any]]

The full sequence of columns referenced by this attribute, adjusted for any aliasing in progress.

.. versionadded:: 1.3.17

.. seealso::

:ref:maptojoin - usage example

of_type
of_type(class_: _EntityType[Any]) -> PropComparator[_T_co]

Redefine this object in terms of a polymorphic subclass, :func:_orm.with_polymorphic construct, or :func:_orm.aliased construct.

Returns a new PropComparator from which further criterion can be evaluated.

e.g.::

query.join(Company.employees.of_type(Engineer)).\
   filter(Engineer.name=='foo')

:param \class_: a class or mapper indicating that criterion will be against this specific subclass.

.. seealso::

:ref:`orm_queryguide_joining_relationships_aliased` - in the
:ref:`queryguide_toplevel`

:ref:`inheritance_of_type`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]:
    r"""Redefine this object in terms of a polymorphic subclass,
    :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased`
    construct.

    Returns a new PropComparator from which further criterion can be
    evaluated.

    e.g.::

        query.join(Company.employees.of_type(Engineer)).\
           filter(Engineer.name=='foo')

    :param \class_: a class or mapper indicating that criterion will be
        against this specific subclass.

    .. seealso::

        :ref:`orm_queryguide_joining_relationships_aliased` - in the
        :ref:`queryguide_toplevel`

        :ref:`inheritance_of_type`

    """

    return self.operate(PropComparator.of_type_op, class_)  # type: ignore
and_
and_(
    *criteria: _ColumnExpressionArgument[bool],
) -> PropComparator[bool]

Add additional criteria to the ON clause that's represented by this relationship attribute.

E.g.::

stmt = select(User).join(
    User.addresses.and_(Address.email_address != 'foo')
)

stmt = select(User).options(
    joinedload(User.addresses.and_(Address.email_address != 'foo'))
)

.. versionadded:: 1.4

.. seealso::

:ref:`orm_queryguide_join_on_augmented`

:ref:`loader_option_criteria`

:func:`.with_loader_criteria`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def and_(
    self, *criteria: _ColumnExpressionArgument[bool]
) -> PropComparator[bool]:
    """Add additional criteria to the ON clause that's represented by this
    relationship attribute.

    E.g.::


        stmt = select(User).join(
            User.addresses.and_(Address.email_address != 'foo')
        )

        stmt = select(User).options(
            joinedload(User.addresses.and_(Address.email_address != 'foo'))
        )

    .. versionadded:: 1.4

    .. seealso::

        :ref:`orm_queryguide_join_on_augmented`

        :ref:`loader_option_criteria`

        :func:`.with_loader_criteria`

    """
    return self.operate(operators.and_, *criteria)  # type: ignore
any
any(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Return a SQL expression representing true if this element references a member which meets the given criterion.

The usual implementation of any() is :meth:.Relationship.Comparator.any.

:param criterion: an optional ClauseElement formulated against the member class' table or attributes.

:param **kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def any(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    r"""Return a SQL expression representing true if this element
    references a member which meets the given criterion.

    The usual implementation of ``any()`` is
    :meth:`.Relationship.Comparator.any`.

    :param criterion: an optional ClauseElement formulated against the
      member class' table or attributes.

    :param \**kwargs: key/value pairs corresponding to member class
      attribute names which will be compared via equality to the
      corresponding values.

    """

    return self.operate(PropComparator.any_op, criterion, **kwargs)
has
has(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Return a SQL expression representing true if this element references a member which meets the given criterion.

The usual implementation of has() is :meth:.Relationship.Comparator.has.

:param criterion: an optional ClauseElement formulated against the member class' table or attributes.

:param **kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def has(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    r"""Return a SQL expression representing true if this element
    references a member which meets the given criterion.

    The usual implementation of ``has()`` is
    :meth:`.Relationship.Comparator.has`.

    :param criterion: an optional ClauseElement formulated against the
      member class' table or attributes.

    :param \**kwargs: key/value pairs corresponding to member class
      attribute names which will be compared via equality to the
      corresponding values.

    """

    return self.operate(PropComparator.has_op, criterion, **kwargs)
property
property() -> MapperProperty[_T_co]

Return the :class:.MapperProperty associated with this :class:.PropComparator.

Return values here will commonly be instances of :class:.ColumnProperty or :class:.Relationship.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.non_memoized_property
def property(self) -> MapperProperty[_T_co]:
    """Return the :class:`.MapperProperty` associated with this
    :class:`.PropComparator`.


    Return values here will commonly be instances of
    :class:`.ColumnProperty` or :class:`.Relationship`.


    """
    return self.prop
adapt_to_entity
adapt_to_entity(
    adapt_to_entity: AliasedInsp[Any],
) -> PropComparator[_T_co]

Return a copy of this PropComparator which will use the given :class:.AliasedInsp to produce corresponding expressions.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def adapt_to_entity(
    self, adapt_to_entity: AliasedInsp[Any]
) -> PropComparator[_T_co]:
    """Return a copy of this PropComparator which will use the given
    :class:`.AliasedInsp` to produce corresponding expressions.
    """
    return self.__class__(self.prop, self._parententity, adapt_to_entity)
adapter
adapter() -> Optional[_ORMAdapterProto]

Produce a callable that adapts column expressions to suit an aliased version of this comparator.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.ro_non_memoized_property
def adapter(self) -> Optional[_ORMAdapterProto]:
    """Produce a callable that adapts column expressions
    to suit an aliased version of this comparator.

    """
    if self._adapt_to_entity is None:
        return None
    else:
        return self._adapt_to_entity._orm_adapt_element

found_in_pep593_annotated

found_in_pep593_annotated() -> Any

return a copy of this object to use in declarative when the object is found inside of an Annotated object.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def found_in_pep593_annotated(self) -> Any:
    """return a copy of this object to use in declarative when the
    object is found inside of an Annotated object."""

    raise NotImplementedError(
        f"Use of the {self.__class__} construct inside of an "
        f"Annotated object is not yet supported."
    )

cascade_iterator

cascade_iterator(
    type_: str,
    state: InstanceState[Any],
    dict_: _InstanceDict,
    visited_states: Set[InstanceState[Any]],
    halt_on: Optional[
        Callable[[InstanceState[Any]], bool]
    ] = None,
) -> Iterator[
    Tuple[
        object,
        Mapper[Any],
        InstanceState[Any],
        _InstanceDict,
    ]
]

Iterate through instances related to the given instance for a particular 'cascade', starting with this MapperProperty.

Return an iterator3-tuples (instance, mapper, state).

Note that the 'cascade' collection on this MapperProperty is checked first for the given type before cascade_iterator is called.

This method typically only applies to Relationship.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def cascade_iterator(
    self,
    type_: str,
    state: InstanceState[Any],
    dict_: _InstanceDict,
    visited_states: Set[InstanceState[Any]],
    halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
) -> Iterator[
    Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
]:
    """Iterate through instances related to the given instance for
    a particular 'cascade', starting with this MapperProperty.

    Return an iterator3-tuples (instance, mapper, state).

    Note that the 'cascade' collection on this MapperProperty is
    checked first for the given type before cascade_iterator is called.

    This method typically only applies to Relationship.

    """

    return iter(())

set_parent

set_parent(parent: Mapper[Any], init: bool) -> None

Set the parent mapper that references this MapperProperty.

This method is overridden by some subclasses to perform extra setup when the mapper is first known.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def set_parent(self, parent: Mapper[Any], init: bool) -> None:
    """Set the parent mapper that references this MapperProperty.

    This method is overridden by some subclasses to perform extra
    setup when the mapper is first known.

    """
    self.parent = parent

init

init() -> None

Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def init(self) -> None:
    """Called after all mappers are created to assemble
    relationships between mappers and perform other post-mapper-creation
    initialization steps.


    """
    self._configure_started = True
    self.do_init()
    self._configure_finished = True

DeclarativeMeta

DeclarativeMeta(
    classname: Any, bases: Any, dict_: Any, **kw: Any
)

Bases: DeclarativeAttributeIntercept

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def __init__(
    cls, classname: Any, bases: Any, dict_: Any, **kw: Any
) -> None:
    # use cls.__dict__, which can be modified by an
    # __init_subclass__() method (#7900)
    dict_ = cls.__dict__

    # early-consume registry from the initial declarative base,
    # assign privately to not conflict with subclass attributes named
    # "registry"
    reg = getattr(cls, "_sa_registry", None)
    if reg is None:
        reg = dict_.get("registry", None)
        if not isinstance(reg, registry):
            raise exc.InvalidRequestError(
                "Declarative base class has no 'registry' attribute, "
                "or registry is not a sqlalchemy.orm.registry() object"
            )
        else:
            cls._sa_registry = reg

    if not cls.__dict__.get("__abstract__", False):
        _as_declarative(reg, cls, dict_)
    type.__init__(cls, classname, bases, dict_)

InstanceState

InstanceState(obj: _O, manager: ClassManager[_O])

Bases: InspectionAttrInfo, Generic[_O]

tracks state information at the instance level.

The :class:.InstanceState is a key object used by the SQLAlchemy ORM in order to track the state of an object; it is created the moment an object is instantiated, typically as a result of :term:instrumentation which SQLAlchemy applies to the __init__() method of the class.

:class:.InstanceState is also a semi-public object, available for runtime inspection as to the state of a mapped instance, including information such as its current status within a particular :class:.Session and details about data on individual attributes. The public API in order to acquire a :class:.InstanceState object is to use the :func:_sa.inspect system::

>>> from sqlalchemy import inspect
>>> insp = inspect(some_mapped_object)
>>> insp.attrs.nickname.history
History(added=['new nickname'], unchanged=(), deleted=['nickname'])

.. seealso::

:ref:`orm_mapper_inspection_instancestate`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
def __init__(self, obj: _O, manager: ClassManager[_O]):
    self.class_ = obj.__class__
    self.manager = manager
    self.obj = weakref.ref(obj, self._cleanup)
    self.committed_state = {}
    self.expired_attributes = set()

is_selectable class-attribute instance-attribute

is_selectable = False

Return True if this object is an instance of :class:_expression.Selectable.

is_aliased_class class-attribute instance-attribute

is_aliased_class = False

True if this object is an instance of :class:.AliasedClass.

is_mapper class-attribute instance-attribute

is_mapper = False

True if this object is an instance of :class:_orm.Mapper.

is_bundle class-attribute instance-attribute

is_bundle = False

True if this object is an instance of :class:.Bundle.

is_property class-attribute instance-attribute

is_property = False

True if this object is an instance of :class:.MapperProperty.

is_attribute class-attribute instance-attribute

is_attribute = False

True if this object is a Python :term:descriptor.

This can refer to one of many types. Usually a :class:.QueryableAttribute which handles attributes events on behalf of a :class:.MapperProperty. But can also be an extension type such as :class:.AssociationProxy or :class:.hybrid_property. The :attr:.InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

.. seealso::

:attr:`_orm.Mapper.all_orm_descriptors`

is_clause_element class-attribute instance-attribute

is_clause_element = False

True if this object is an instance of :class:_expression.ClauseElement.

extension_type class-attribute instance-attribute

extension_type: InspectionAttrExtensionType = NOT_EXTENSION

The extension type, if any. Defaults to :attr:.interfaces.NotExtension.NOT_EXTENSION

.. seealso::

:class:`.HybridExtensionType`

:class:`.AssociationProxyExtensionType`

expired_attributes instance-attribute

expired_attributes: Set[str] = set()

The set of keys which are 'expired' to be loaded by the manager's deferred scalar loader, assuming no pending changes.

see also the unmodified collection which is intersected against this set when a refresh operation occurs.

callables instance-attribute

callables: Dict[
    str, Callable[[InstanceState[_O], PassiveFlag], Any]
]

A namespace where a per-state loader callable can be associated.

In SQLAlchemy 1.0, this is only used for lazy loaders / deferred loaders that were set up via query option.

Previously, callables was used also to indicate expired attributes by storing a link to the InstanceState itself in this dictionary. This role is now handled by the expired_attributes set.

transient property

transient: bool

Return True if the object is :term:transient.

.. seealso::

:ref:`session_object_states`

pending property

pending: bool

Return True if the object is :term:pending.

.. seealso::

:ref:`session_object_states`

deleted property

deleted: bool

Return True if the object is :term:deleted.

An object that is in the deleted state is guaranteed to not be within the :attr:.Session.identity_map of its parent :class:.Session; however if the session's transaction is rolled back, the object will be restored to the persistent state and the identity map.

.. note::

The :attr:`.InstanceState.deleted` attribute refers to a specific
state of the object that occurs between the "persistent" and
"detached" states; once the object is :term:`detached`, the
:attr:`.InstanceState.deleted` attribute **no longer returns
True**; in order to detect that a state was deleted, regardless
of whether or not the object is associated with a
:class:`.Session`, use the :attr:`.InstanceState.was_deleted`
accessor.

.. versionadded: 1.1

.. seealso::

:ref:`session_object_states`

was_deleted property

was_deleted: bool

Return True if this object is or was previously in the "deleted" state and has not been reverted to persistent.

This flag returns True once the object was deleted in flush. When the object is expunged from the session either explicitly or via transaction commit and enters the "detached" state, this flag will continue to report True.

.. seealso::

:attr:`.InstanceState.deleted` - refers to the "deleted" state

:func:`.orm.util.was_deleted` - standalone function

:ref:`session_object_states`

persistent property

persistent: bool

Return True if the object is :term:persistent.

An object that is in the persistent state is guaranteed to be within the :attr:.Session.identity_map of its parent :class:.Session.

.. seealso::

:ref:`session_object_states`

detached property

detached: bool

Return True if the object is :term:detached.

.. seealso::

:ref:`session_object_states`

session property

session: Optional[Session]

Return the owning :class:.Session for this instance, or None if none available.

Note that the result here can in some cases be different from that of obj in session; an object that's been deleted will report as not in session, however if the transaction is still in progress, this attribute will still refer to that session. Only when the transaction is completed does the object become fully detached under normal circumstances.

.. seealso::

:attr:`_orm.InstanceState.async_session`

async_session property

async_session: Optional[AsyncSession]

Return the owning :class:_asyncio.AsyncSession for this instance, or None if none available.

This attribute is only non-None when the :mod:sqlalchemy.ext.asyncio API is in use for this ORM object. The returned :class:_asyncio.AsyncSession object will be a proxy for the :class:_orm.Session object that would be returned from the :attr:_orm.InstanceState.session attribute for this :class:_orm.InstanceState.

.. versionadded:: 1.4.18

.. seealso::

:ref:`asyncio_toplevel`

object property

object: Optional[_O]

Return the mapped object represented by this :class:.InstanceState.

Returns None if the object has been garbage collected

identity property

identity: Optional[Tuple[Any, ...]]

Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to :meth:_query.Query.get.

Returns None if the object has no primary key identity.

.. note:: An object which is :term:transient or :term:pending does not have a mapped identity until it is flushed, even if its attributes include primary key values.

identity_key property

identity_key: Optional[_IdentityKeyType[_O]]

Return the identity key for the mapped object.

This is the key used to locate the object within the :attr:.Session.identity_map mapping. It contains the identity as returned by :attr:.identity within it.

has_identity property

has_identity: bool

Return True if this object has an identity key.

This should always have the same value as the expression state.persistent or state.detached.

dict property

dict: _InstanceDict

Return the instance dict used by the object.

Under normal circumstances, this is always synonymous with the __dict__ attribute of the mapped object, unless an alternative instrumentation system has been configured.

In the case that the actual object has been garbage collected, this accessor returns a blank dictionary.

unmodified property

unmodified: Set[str]

Return the set of keys which have no uncommitted changes

unloaded property

unloaded: Set[str]

Return the set of keys which do not have a loaded value.

This includes expired attributes and any other attribute that was never populated or modified.

unloaded_expirable property

unloaded_expirable: Set[str]

Synonymous with :attr:.InstanceState.unloaded.

This attribute was added as an implementation-specific detail at some point and should be considered to be private.

info

info() -> _InfoType

Info dictionary associated with the object, allowing user-defined data to be associated with this :class:.InspectionAttr.

The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:.column_property, :func:_orm.relationship, or :func:.composite functions.

.. seealso::

:attr:`.QueryableAttribute.info`

:attr:`.SchemaItem.info`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/base.py
@util.ro_memoized_property
def info(self) -> _InfoType:
    """Info dictionary associated with the object, allowing user-defined
    data to be associated with this :class:`.InspectionAttr`.

    The dictionary is generated when first accessed.  Alternatively,
    it can be specified as a constructor argument to the
    :func:`.column_property`, :func:`_orm.relationship`, or
    :func:`.composite`
    functions.

    .. seealso::

        :attr:`.QueryableAttribute.info`

        :attr:`.SchemaItem.info`

    """
    return {}

attrs

attrs() -> ReadOnlyProperties[AttributeState]

Return a namespace representing each attribute on the mapped object, including its current value and history.

The returned object is an instance of :class:.AttributeState. This object allows inspection of the current data within an attribute as well as attribute history since the last flush.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
@util.memoized_property
def attrs(self) -> util.ReadOnlyProperties[AttributeState]:
    """Return a namespace representing each attribute on
    the mapped object, including its current value
    and history.

    The returned object is an instance of :class:`.AttributeState`.
    This object allows inspection of the current data
    within an attribute as well as attribute history
    since the last flush.

    """
    return util.ReadOnlyProperties(
        {key: AttributeState(self, key) for key in self.manager}
    )

mapper

mapper() -> Mapper[_O]

Return the :class:_orm.Mapper used for this mapped object.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
@util.memoized_property
def mapper(self) -> Mapper[_O]:
    """Return the :class:`_orm.Mapper` used for this mapped object."""
    return self.manager.mapper

unmodified_intersection

unmodified_intersection(keys: Iterable[str]) -> Set[str]

Return self.unmodified.intersection(keys).

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/state.py
def unmodified_intersection(self, keys: Iterable[str]) -> Set[str]:
    """Return self.unmodified.intersection(keys)."""

    return (
        set(keys)
        .intersection(self.manager)
        .difference(self.committed_state)
    )

InstrumentedAttribute

InstrumentedAttribute(
    class_: _ExternalEntityType[_O],
    key: str,
    parententity: _InternalEntityType[_O],
    comparator: PropComparator[_T_co],
    impl: Optional[AttributeImpl] = None,
    of_type: Optional[_InternalEntityType[Any]] = None,
    extra_criteria: Tuple[ColumnElement[bool], ...] = (),
)

Bases: QueryableAttribute[_T]

Class bound instrumented attribute which adds basic :term:descriptor methods.

See :class:.QueryableAttribute for a description of most features.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/attributes.py
def __init__(
    self,
    class_: _ExternalEntityType[_O],
    key: str,
    parententity: _InternalEntityType[_O],
    comparator: interfaces.PropComparator[_T_co],
    impl: Optional[AttributeImpl] = None,
    of_type: Optional[_InternalEntityType[Any]] = None,
    extra_criteria: Tuple[ColumnElement[bool], ...] = (),
):
    self.class_ = class_
    self.key = key

    self._parententity = self.parent = parententity

    # this attribute is non-None after mappers are set up, however in the
    # interim class manager setup, there's a check for None to see if it
    # needs to be populated, so we assign None here leaving the attribute
    # in a temporarily not-type-correct state
    self.impl = impl  # type: ignore

    assert comparator is not None
    self.comparator = comparator
    self._of_type = of_type
    self._extra_criteria = extra_criteria
    self._doc = None

    manager = opt_manager_of_class(class_)
    # manager is None in the case of AliasedClass
    if manager:
        # propagate existing event listeners from
        # immediate superclass
        for base in manager._bases:
            if key in base:
                self.dispatch._update(base[key].dispatch)
                if base[key].dispatch._active_history:
                    self.dispatch._active_history = True  # type: ignore

timetuple class-attribute instance-attribute

timetuple: Literal[None] = None

Hack, allows datetime objects to be compared on the LHS.

info property

info: _InfoType

Return the 'info' dictionary for the underlying SQL element.

The behavior here is as follows:

  • If the attribute is a column-mapped property, i.e. :class:.ColumnProperty, which is mapped directly to a schema-level :class:_schema.Column object, this attribute will return the :attr:.SchemaItem.info dictionary associated with the core-level :class:_schema.Column object.

  • If the attribute is a :class:.ColumnProperty but is mapped to any other kind of SQL expression other than a :class:_schema.Column, the attribute will refer to the :attr:.MapperProperty.info dictionary associated directly with the :class:.ColumnProperty, assuming the SQL expression itself does not have its own .info attribute (which should be the case, unless a user-defined SQL construct has defined one).

  • If the attribute refers to any other kind of :class:.MapperProperty, including :class:.Relationship, the attribute will refer to the :attr:.MapperProperty.info dictionary associated with that :class:.MapperProperty.

  • To access the :attr:.MapperProperty.info dictionary of the :class:.MapperProperty unconditionally, including for a :class:.ColumnProperty that's associated directly with a :class:_schema.Column, the attribute can be referred to using :attr:.QueryableAttribute.property attribute, as MyClass.someattribute.property.info.

.. seealso::

:attr:`.SchemaItem.info`

:attr:`.MapperProperty.info`

is_selectable class-attribute instance-attribute

is_selectable = False

Return True if this object is an instance of :class:_expression.Selectable.

is_aliased_class class-attribute instance-attribute

is_aliased_class = False

True if this object is an instance of :class:.AliasedClass.

is_instance class-attribute instance-attribute

is_instance = False

True if this object is an instance of :class:.InstanceState.

is_mapper class-attribute instance-attribute

is_mapper = False

True if this object is an instance of :class:_orm.Mapper.

is_bundle class-attribute instance-attribute

is_bundle = False

True if this object is an instance of :class:.Bundle.

is_property class-attribute instance-attribute

is_property = False

True if this object is an instance of :class:.MapperProperty.

is_clause_element class-attribute instance-attribute

is_clause_element = False

True if this object is an instance of :class:_expression.ClauseElement.

extension_type class-attribute instance-attribute

extension_type: InspectionAttrExtensionType = NOT_EXTENSION

The extension type, if any. Defaults to :attr:.interfaces.NotExtension.NOT_EXTENSION

.. seealso::

:class:`.HybridExtensionType`

:class:`.AssociationProxyExtensionType`

parent instance-attribute

parent: _InternalEntityType[Any]

Return an inspection instance representing the parent.

This will be either an instance of :class:_orm.Mapper or :class:.AliasedInsp, depending upon the nature of the parent entity which this attribute is associated with.

expression instance-attribute

expression: ColumnElement[_T_co]

The SQL expression object represented by this :class:.QueryableAttribute.

This will typically be an instance of a :class:_sql.ColumnElement subclass representing a column expression.

inherit_cache class-attribute instance-attribute

inherit_cache = True

:meta private:

any

any(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Return a SQL expression representing true if this element references a member which meets the given criterion.

The usual implementation of any() is :meth:.Relationship.Comparator.any.

:param criterion: an optional ClauseElement formulated against the member class' table or attributes.

:param **kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def any(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    r"""Return a SQL expression representing true if this element
    references a member which meets the given criterion.

    The usual implementation of ``any()`` is
    :meth:`.Relationship.Comparator.any`.

    :param criterion: an optional ClauseElement formulated against the
      member class' table or attributes.

    :param \**kwargs: key/value pairs corresponding to member class
      attribute names which will be compared via equality to the
      corresponding values.

    """

    return self.operate(PropComparator.any_op, criterion, **kwargs)

has

has(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Return a SQL expression representing true if this element references a member which meets the given criterion.

The usual implementation of has() is :meth:.Relationship.Comparator.has.

:param criterion: an optional ClauseElement formulated against the member class' table or attributes.

:param **kwargs: key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def has(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    r"""Return a SQL expression representing true if this element
    references a member which meets the given criterion.

    The usual implementation of ``has()`` is
    :meth:`.Relationship.Comparator.has`.

    :param criterion: an optional ClauseElement formulated against the
      member class' table or attributes.

    :param \**kwargs: key/value pairs corresponding to member class
      attribute names which will be compared via equality to the
      corresponding values.

    """

    return self.operate(PropComparator.has_op, criterion, **kwargs)

property

property() -> MapperProperty[_T_co]

Return the :class:.MapperProperty associated with this :class:.PropComparator.

Return values here will commonly be instances of :class:.ColumnProperty or :class:.Relationship.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.non_memoized_property
def property(self) -> MapperProperty[_T_co]:
    """Return the :class:`.MapperProperty` associated with this
    :class:`.PropComparator`.


    Return values here will commonly be instances of
    :class:`.ColumnProperty` or :class:`.Relationship`.


    """
    return self.prop

adapter

adapter() -> Optional[_ORMAdapterProto]

Produce a callable that adapts column expressions to suit an aliased version of this comparator.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.ro_non_memoized_property
def adapter(self) -> Optional[_ORMAdapterProto]:
    """Produce a callable that adapts column expressions
    to suit an aliased version of this comparator.

    """
    if self._adapt_to_entity is None:
        return None
    else:
        return self._adapt_to_entity._orm_adapt_element

InstrumentedDict

Bases: Dict[_KT, _VT]

An instrumented version of the built-in dict.

InstrumentedList

Bases: List[_T]

An instrumented version of the built-in list.

InstrumentedSet

Bases: Set[_T]

An instrumented version of the built-in set.

Load

Load(entity: _EntityType[Any])

Bases: _AbstractLoad

Represents loader options which modify the state of a ORM-enabled :class:_sql.Select or a legacy :class:_query.Query in order to affect how various mapped attributes are loaded.

The :class:_orm.Load object is in most cases used implicitly behind the scenes when one makes use of a query option like :func:_orm.joinedload, :func:_orm.defer, or similar. It typically is not instantiated directly except for in some very specific cases.

.. seealso::

:ref:`orm_queryguide_relationship_per_entity_wildcard` - illustrates an
example where direct use of :class:`_orm.Load` may be useful
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def __init__(self, entity: _EntityType[Any]):
    insp = cast("Union[Mapper[Any], AliasedInsp[Any]]", inspect(entity))
    insp._post_inspect

    self.path = insp._path_registry
    self.context = ()
    self.propagate_to_loaders = False
    self.additional_source_entities = ()

inherit_cache class-attribute instance-attribute

inherit_cache: Optional[bool] = None

Indicate if this :class:.HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

.. seealso::

:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.

get_children

get_children(
    *, omit_attrs: Tuple[str, ...] = (), **kw: Any
) -> Iterable[HasTraverseInternals]

Return immediate child :class:.visitors.HasTraverseInternals elements of this :class:.visitors.HasTraverseInternals.

This is used for visit traversal.

**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py
@util.preload_module("sqlalchemy.sql.traversals")
def get_children(
    self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any
) -> Iterable[HasTraverseInternals]:
    r"""Return immediate child :class:`.visitors.HasTraverseInternals`
    elements of this :class:`.visitors.HasTraverseInternals`.

    This is used for visit traversal.

    \**kw may contain flags that change the collection that is
    returned, for example to return a subset of items in order to
    cut down on larger traversals, or to return child items from a
    different context (such as schema-level collections instead of
    clause-level).

    """

    traversals = util.preloaded.sql_traversals

    try:
        traverse_internals = self._traverse_internals
    except AttributeError:
        # user-defined classes may not have a _traverse_internals
        return []

    dispatch = traversals._get_children.run_generated_dispatch
    return itertools.chain.from_iterable(
        meth(obj, **kw)
        for attrname, obj, meth in dispatch(
            self, traverse_internals, "_generated_get_children_traversal"
        )
        if attrname not in omit_attrs and obj is not None
    )

contains_eager

contains_eager(
    attr: _AttrType,
    alias: Optional[_FromClauseArgument] = None,
    _is_chain: bool = False,
) -> Self

Indicate that the given attribute should be eagerly loaded from columns stated manually in the query.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

The option is used in conjunction with an explicit join that loads the desired rows, i.e.::

sess.query(Order).\
        join(Order.user).\
        options(contains_eager(Order.user))

The above query would join from the Order entity to its related User entity, and the returned Order objects would have the Order.user attribute pre-populated.

It may also be used for customizing the entries in an eagerly loaded collection; queries will normally want to use the :ref:orm_queryguide_populate_existing execution option assuming the primary collection of parent objects may already have been loaded::

sess.query(User).\
    join(User.addresses).\
    filter(Address.email_address.like('%@aol.com')).\
    options(contains_eager(User.addresses)).\
    populate_existing()

See the section :ref:contains_eager for complete usage details.

.. seealso::

:ref:`loading_toplevel`

:ref:`contains_eager`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def contains_eager(
    self,
    attr: _AttrType,
    alias: Optional[_FromClauseArgument] = None,
    _is_chain: bool = False,
) -> Self:
    r"""Indicate that the given attribute should be eagerly loaded from
    columns stated manually in the query.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    The option is used in conjunction with an explicit join that loads
    the desired rows, i.e.::

        sess.query(Order).\
                join(Order.user).\
                options(contains_eager(Order.user))

    The above query would join from the ``Order`` entity to its related
    ``User`` entity, and the returned ``Order`` objects would have the
    ``Order.user`` attribute pre-populated.

    It may also be used for customizing the entries in an eagerly loaded
    collection; queries will normally want to use the
    :ref:`orm_queryguide_populate_existing` execution option assuming the
    primary collection of parent objects may already have been loaded::

        sess.query(User).\
            join(User.addresses).\
            filter(Address.email_address.like('%@aol.com')).\
            options(contains_eager(User.addresses)).\
            populate_existing()

    See the section :ref:`contains_eager` for complete usage details.

    .. seealso::

        :ref:`loading_toplevel`

        :ref:`contains_eager`

    """
    if alias is not None:
        if not isinstance(alias, str):
            coerced_alias = coercions.expect(roles.FromClauseRole, alias)
        else:
            util.warn_deprecated(
                "Passing a string name for the 'alias' argument to "
                "'contains_eager()` is deprecated, and will not work in a "
                "future release.  Please use a sqlalchemy.alias() or "
                "sqlalchemy.orm.aliased() construct.",
                version="1.4",
            )
            coerced_alias = alias

    elif getattr(attr, "_of_type", None):
        assert isinstance(attr, QueryableAttribute)
        ot: Optional[_InternalEntityType[Any]] = inspect(attr._of_type)
        assert ot is not None
        coerced_alias = ot.selectable
    else:
        coerced_alias = None

    cloned = self._set_relationship_strategy(
        attr,
        {"lazy": "joined"},
        propagate_to_loaders=False,
        opts={"eager_from_alias": coerced_alias},
        _reconcile_to_other=True if _is_chain else None,
    )
    return cloned

load_only

load_only(
    *attrs: _AttrType, raiseload: bool = False
) -> Self

Indicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

Example - given a class User, load only the name and fullname attributes::

session.query(User).options(load_only(User.name, User.fullname))

Example - given a relationship User.addresses -> Address, specify subquery loading for the User.addresses collection, but on each Address object load only the email_address attribute::

session.query(User).options(
    subqueryload(User.addresses).load_only(Address.email_address)
)

For a statement that has multiple entities, the lead entity can be specifically referred to using the :class:_orm.Load constructor::

stmt = select(User, Address).join(User.addresses).options(
            Load(User).load_only(User.name, User.fullname),
            Load(Address).load_only(Address.email_address)
        )

:param *attrs: Attributes to be loaded, all others will be deferred.

:param raiseload: raise :class:.InvalidRequestError rather than lazy loading a value when a deferred attribute is accessed. Used to prevent unwanted SQL from being emitted.

.. versionadded:: 2.0

.. seealso::

:ref:`orm_queryguide_column_deferral` - in the
:ref:`queryguide_toplevel`

:param *attrs: Attributes to be loaded, all others will be deferred.

:param raiseload: raise :class:.InvalidRequestError rather than lazy loading a value when a deferred attribute is accessed. Used to prevent unwanted SQL from being emitted.

.. versionadded:: 2.0

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def load_only(self, *attrs: _AttrType, raiseload: bool = False) -> Self:
    r"""Indicate that for a particular entity, only the given list
    of column-based attribute names should be loaded; all others will be
    deferred.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    Example - given a class ``User``, load only the ``name`` and
    ``fullname`` attributes::

        session.query(User).options(load_only(User.name, User.fullname))

    Example - given a relationship ``User.addresses -> Address``, specify
    subquery loading for the ``User.addresses`` collection, but on each
    ``Address`` object load only the ``email_address`` attribute::

        session.query(User).options(
            subqueryload(User.addresses).load_only(Address.email_address)
        )

    For a statement that has multiple entities,
    the lead entity can be
    specifically referred to using the :class:`_orm.Load` constructor::

        stmt = select(User, Address).join(User.addresses).options(
                    Load(User).load_only(User.name, User.fullname),
                    Load(Address).load_only(Address.email_address)
                )

    :param \*attrs: Attributes to be loaded, all others will be deferred.

    :param raiseload: raise :class:`.InvalidRequestError` rather than
     lazy loading a value when a deferred attribute is accessed. Used
     to prevent unwanted SQL from being emitted.

     .. versionadded:: 2.0

    .. seealso::

        :ref:`orm_queryguide_column_deferral` - in the
        :ref:`queryguide_toplevel`

    :param \*attrs: Attributes to be loaded, all others will be deferred.

    :param raiseload: raise :class:`.InvalidRequestError` rather than
     lazy loading a value when a deferred attribute is accessed. Used
     to prevent unwanted SQL from being emitted.

     .. versionadded:: 2.0

    """
    cloned = self._set_column_strategy(
        attrs,
        {"deferred": False, "instrument": True},
    )

    wildcard_strategy = {"deferred": True, "instrument": True}
    if raiseload:
        wildcard_strategy["raiseload"] = True

    cloned = cloned._set_column_strategy(
        ("*",),
        wildcard_strategy,
    )
    return cloned

joinedload

joinedload(
    attr: _AttrType, innerjoin: Optional[bool] = None
) -> Self

Indicate that the given attribute should be loaded using joined eager loading.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

examples::

# joined-load the "orders" collection on "User"
query(User).options(joinedload(User.orders))

# joined-load Order.items and then Item.keywords
query(Order).options(
    joinedload(Order.items).joinedload(Item.keywords))

# lazily load Order.items, but when Items are loaded,
# joined-load the keywords collection
query(Order).options(
    lazyload(Order.items).joinedload(Item.keywords))

:param innerjoin: if True, indicates that the joined eager load should use an inner join instead of the default of left outer join::

query(Order).options(joinedload(Order.user, innerjoin=True))

In order to chain multiple eager joins together where some may be OUTER and others INNER, right-nested joins are used to link them::

query(A).options(
    joinedload(A.bs, innerjoin=False).
        joinedload(B.cs, innerjoin=True)
)

The above query, linking A.bs via "outer" join and B.cs via "inner" join would render the joins as "a LEFT OUTER JOIN (b JOIN c)". When using older versions of SQLite (< 3.7.16), this form of JOIN is translated to use full subqueries as this syntax is otherwise not directly supported.

The innerjoin flag can also be stated with the term "unnested". This indicates that an INNER JOIN should be used, unless the join is linked to a LEFT OUTER JOIN to the left, in which case it will render as LEFT OUTER JOIN. For example, supposing A.bs is an outerjoin::

query(A).options(
    joinedload(A.bs).
        joinedload(B.cs, innerjoin="unnested")
)

The above join will render as "a LEFT OUTER JOIN b LEFT OUTER JOIN c", rather than as "a LEFT OUTER JOIN (b JOIN c)".

.. note:: The "unnested" flag does not affect the JOIN rendered from a many-to-many association table, e.g. a table configured as :paramref:_orm.relationship.secondary, to the target table; for correctness of results, these joins are always INNER and are therefore right-nested if linked to an OUTER join.

.. note::

The joins produced by :func:`_orm.joinedload` are **anonymously
aliased**. The criteria by which the join proceeds cannot be
modified, nor can the ORM-enabled :class:`_sql.Select` or legacy
:class:`_query.Query` refer to these joins in any way, including
ordering. See :ref:`zen_of_eager_loading` for further detail.

To produce a specific SQL JOIN which is explicitly available, use
:meth:`_sql.Select.join` and :meth:`_query.Query.join`. To combine
explicit JOINs with eager loading of collections, use
:func:`_orm.contains_eager`; see :ref:`contains_eager`.

.. seealso::

:ref:`loading_toplevel`

:ref:`joined_eager_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def joinedload(
    self,
    attr: _AttrType,
    innerjoin: Optional[bool] = None,
) -> Self:
    """Indicate that the given attribute should be loaded using joined
    eager loading.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    examples::

        # joined-load the "orders" collection on "User"
        query(User).options(joinedload(User.orders))

        # joined-load Order.items and then Item.keywords
        query(Order).options(
            joinedload(Order.items).joinedload(Item.keywords))

        # lazily load Order.items, but when Items are loaded,
        # joined-load the keywords collection
        query(Order).options(
            lazyload(Order.items).joinedload(Item.keywords))

    :param innerjoin: if ``True``, indicates that the joined eager load
     should use an inner join instead of the default of left outer join::

        query(Order).options(joinedload(Order.user, innerjoin=True))

    In order to chain multiple eager joins together where some may be
    OUTER and others INNER, right-nested joins are used to link them::

        query(A).options(
            joinedload(A.bs, innerjoin=False).
                joinedload(B.cs, innerjoin=True)
        )

    The above query, linking A.bs via "outer" join and B.cs via "inner"
    join would render the joins as "a LEFT OUTER JOIN (b JOIN c)". When
    using older versions of SQLite (< 3.7.16), this form of JOIN is
    translated to use full subqueries as this syntax is otherwise not
    directly supported.

    The ``innerjoin`` flag can also be stated with the term ``"unnested"``.
    This indicates that an INNER JOIN should be used, *unless* the join
    is linked to a LEFT OUTER JOIN to the left, in which case it
    will render as LEFT OUTER JOIN.  For example, supposing ``A.bs``
    is an outerjoin::

        query(A).options(
            joinedload(A.bs).
                joinedload(B.cs, innerjoin="unnested")
        )

    The above join will render as "a LEFT OUTER JOIN b LEFT OUTER JOIN c",
    rather than as "a LEFT OUTER JOIN (b JOIN c)".

    .. note:: The "unnested" flag does **not** affect the JOIN rendered
        from a many-to-many association table, e.g. a table configured as
        :paramref:`_orm.relationship.secondary`, to the target table; for
        correctness of results, these joins are always INNER and are
        therefore right-nested if linked to an OUTER join.

    .. note::

        The joins produced by :func:`_orm.joinedload` are **anonymously
        aliased**. The criteria by which the join proceeds cannot be
        modified, nor can the ORM-enabled :class:`_sql.Select` or legacy
        :class:`_query.Query` refer to these joins in any way, including
        ordering. See :ref:`zen_of_eager_loading` for further detail.

        To produce a specific SQL JOIN which is explicitly available, use
        :meth:`_sql.Select.join` and :meth:`_query.Query.join`. To combine
        explicit JOINs with eager loading of collections, use
        :func:`_orm.contains_eager`; see :ref:`contains_eager`.

    .. seealso::

        :ref:`loading_toplevel`

        :ref:`joined_eager_loading`

    """
    loader = self._set_relationship_strategy(
        attr,
        {"lazy": "joined"},
        opts=(
            {"innerjoin": innerjoin}
            if innerjoin is not None
            else util.EMPTY_DICT
        ),
    )
    return loader

subqueryload

subqueryload(attr: _AttrType) -> Self

Indicate that the given attribute should be loaded using subquery eager loading.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

examples::

# subquery-load the "orders" collection on "User"
query(User).options(subqueryload(User.orders))

# subquery-load Order.items and then Item.keywords
query(Order).options(
    subqueryload(Order.items).subqueryload(Item.keywords))

# lazily load Order.items, but when Items are loaded,
# subquery-load the keywords collection
query(Order).options(
    lazyload(Order.items).subqueryload(Item.keywords))

.. seealso::

:ref:`loading_toplevel`

:ref:`subquery_eager_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def subqueryload(self, attr: _AttrType) -> Self:
    """Indicate that the given attribute should be loaded using
    subquery eager loading.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    examples::

        # subquery-load the "orders" collection on "User"
        query(User).options(subqueryload(User.orders))

        # subquery-load Order.items and then Item.keywords
        query(Order).options(
            subqueryload(Order.items).subqueryload(Item.keywords))

        # lazily load Order.items, but when Items are loaded,
        # subquery-load the keywords collection
        query(Order).options(
            lazyload(Order.items).subqueryload(Item.keywords))


    .. seealso::

        :ref:`loading_toplevel`

        :ref:`subquery_eager_loading`

    """
    return self._set_relationship_strategy(attr, {"lazy": "subquery"})

selectinload

selectinload(
    attr: _AttrType, recursion_depth: Optional[int] = None
) -> Self

Indicate that the given attribute should be loaded using SELECT IN eager loading.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

examples::

# selectin-load the "orders" collection on "User"
query(User).options(selectinload(User.orders))

# selectin-load Order.items and then Item.keywords
query(Order).options(
    selectinload(Order.items).selectinload(Item.keywords))

# lazily load Order.items, but when Items are loaded,
# selectin-load the keywords collection
query(Order).options(
    lazyload(Order.items).selectinload(Item.keywords))

:param recursion_depth: optional int; when set to a positive integer in conjunction with a self-referential relationship, indicates "selectin" loading will continue that many levels deep automatically until no items are found.

.. note:: The :paramref:_orm.selectinload.recursion_depth option currently supports only self-referential relationships. There is not yet an option to automatically traverse recursive structures with more than one relationship involved.

Additionally, the :paramref:`_orm.selectinload.recursion_depth`
parameter is new and experimental and should be treated as "alpha"
status for the 2.0 series.

.. versionadded:: 2.0 added :paramref:_orm.selectinload.recursion_depth

.. seealso::

:ref:`loading_toplevel`

:ref:`selectin_eager_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def selectinload(
    self,
    attr: _AttrType,
    recursion_depth: Optional[int] = None,
) -> Self:
    """Indicate that the given attribute should be loaded using
    SELECT IN eager loading.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    examples::

        # selectin-load the "orders" collection on "User"
        query(User).options(selectinload(User.orders))

        # selectin-load Order.items and then Item.keywords
        query(Order).options(
            selectinload(Order.items).selectinload(Item.keywords))

        # lazily load Order.items, but when Items are loaded,
        # selectin-load the keywords collection
        query(Order).options(
            lazyload(Order.items).selectinload(Item.keywords))

    :param recursion_depth: optional int; when set to a positive integer
     in conjunction with a self-referential relationship,
     indicates "selectin" loading will continue that many levels deep
     automatically until no items are found.

     .. note:: The :paramref:`_orm.selectinload.recursion_depth` option
        currently supports only self-referential relationships.  There
        is not yet an option to automatically traverse recursive structures
        with more than one relationship involved.

        Additionally, the :paramref:`_orm.selectinload.recursion_depth`
        parameter is new and experimental and should be treated as "alpha"
        status for the 2.0 series.

     .. versionadded:: 2.0 added
        :paramref:`_orm.selectinload.recursion_depth`


    .. seealso::

        :ref:`loading_toplevel`

        :ref:`selectin_eager_loading`

    """
    return self._set_relationship_strategy(
        attr,
        {"lazy": "selectin"},
        opts={"recursion_depth": recursion_depth},
    )

lazyload

lazyload(attr: _AttrType) -> Self

Indicate that the given attribute should be loaded using "lazy" loading.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

.. seealso::

:ref:`loading_toplevel`

:ref:`lazy_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def lazyload(self, attr: _AttrType) -> Self:
    """Indicate that the given attribute should be loaded using "lazy"
    loading.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    .. seealso::

        :ref:`loading_toplevel`

        :ref:`lazy_loading`

    """
    return self._set_relationship_strategy(attr, {"lazy": "select"})

immediateload

immediateload(
    attr: _AttrType, recursion_depth: Optional[int] = None
) -> Self

Indicate that the given attribute should be loaded using an immediate load with a per-attribute SELECT statement.

The load is achieved using the "lazyloader" strategy and does not fire off any additional eager loaders.

The :func:.immediateload option is superseded in general by the :func:.selectinload option, which performs the same task more efficiently by emitting a SELECT for all loaded objects.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

:param recursion_depth: optional int; when set to a positive integer in conjunction with a self-referential relationship, indicates "selectin" loading will continue that many levels deep automatically until no items are found.

.. note:: The :paramref:_orm.immediateload.recursion_depth option currently supports only self-referential relationships. There is not yet an option to automatically traverse recursive structures with more than one relationship involved.

.. warning:: This parameter is new and experimental and should be treated as "alpha" status

.. versionadded:: 2.0 added :paramref:_orm.immediateload.recursion_depth

.. seealso::

:ref:`loading_toplevel`

:ref:`selectin_eager_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def immediateload(
    self,
    attr: _AttrType,
    recursion_depth: Optional[int] = None,
) -> Self:
    """Indicate that the given attribute should be loaded using
    an immediate load with a per-attribute SELECT statement.

    The load is achieved using the "lazyloader" strategy and does not
    fire off any additional eager loaders.

    The :func:`.immediateload` option is superseded in general
    by the :func:`.selectinload` option, which performs the same task
    more efficiently by emitting a SELECT for all loaded objects.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    :param recursion_depth: optional int; when set to a positive integer
     in conjunction with a self-referential relationship,
     indicates "selectin" loading will continue that many levels deep
     automatically until no items are found.

     .. note:: The :paramref:`_orm.immediateload.recursion_depth` option
        currently supports only self-referential relationships.  There
        is not yet an option to automatically traverse recursive structures
        with more than one relationship involved.

     .. warning:: This parameter is new and experimental and should be
        treated as "alpha" status

     .. versionadded:: 2.0 added
        :paramref:`_orm.immediateload.recursion_depth`


    .. seealso::

        :ref:`loading_toplevel`

        :ref:`selectin_eager_loading`

    """
    loader = self._set_relationship_strategy(
        attr,
        {"lazy": "immediate"},
        opts={"recursion_depth": recursion_depth},
    )
    return loader

noload

noload(attr: _AttrType) -> Self

Indicate that the given relationship attribute should remain unloaded.

The relationship attribute will return None when accessed without producing any loading effect.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

:func:_orm.noload applies to :func:_orm.relationship attributes only.

.. note:: Setting this loading strategy as the default strategy for a relationship using the :paramref:.orm.relationship.lazy parameter may cause issues with flushes, such if a delete operation needs to load related objects and instead None was returned.

.. seealso::

:ref:`loading_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def noload(self, attr: _AttrType) -> Self:
    """Indicate that the given relationship attribute should remain
    unloaded.

    The relationship attribute will return ``None`` when accessed without
    producing any loading effect.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    :func:`_orm.noload` applies to :func:`_orm.relationship` attributes
    only.

    .. note:: Setting this loading strategy as the default strategy
        for a relationship using the :paramref:`.orm.relationship.lazy`
        parameter may cause issues with flushes, such if a delete operation
        needs to load related objects and instead ``None`` was returned.

    .. seealso::

        :ref:`loading_toplevel`

    """

    return self._set_relationship_strategy(attr, {"lazy": "noload"})

raiseload

raiseload(attr: _AttrType, sql_only: bool = False) -> Self

Indicate that the given attribute should raise an error if accessed.

A relationship attribute configured with :func:_orm.raiseload will raise an :exc:~sqlalchemy.exc.InvalidRequestError upon access. The typical way this is useful is when an application is attempting to ensure that all relationship attributes that are accessed in a particular context would have been already loaded via eager loading. Instead of having to read through SQL logs to ensure lazy loads aren't occurring, this strategy will cause them to raise immediately.

:func:_orm.raiseload applies to :func:_orm.relationship attributes only. In order to apply raise-on-SQL behavior to a column-based attribute, use the :paramref:.orm.defer.raiseload parameter on the :func:.defer loader option.

:param sql_only: if True, raise only if the lazy load would emit SQL, but not if it is only checking the identity map, or determining that the related value should just be None due to missing keys. When False, the strategy will raise for all varieties of relationship loading.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

.. seealso::

:ref:`loading_toplevel`

:ref:`prevent_lazy_with_raiseload`

:ref:`orm_queryguide_deferred_raiseload`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def raiseload(self, attr: _AttrType, sql_only: bool = False) -> Self:
    """Indicate that the given attribute should raise an error if accessed.

    A relationship attribute configured with :func:`_orm.raiseload` will
    raise an :exc:`~sqlalchemy.exc.InvalidRequestError` upon access. The
    typical way this is useful is when an application is attempting to
    ensure that all relationship attributes that are accessed in a
    particular context would have been already loaded via eager loading.
    Instead of having to read through SQL logs to ensure lazy loads aren't
    occurring, this strategy will cause them to raise immediately.

    :func:`_orm.raiseload` applies to :func:`_orm.relationship` attributes
    only. In order to apply raise-on-SQL behavior to a column-based
    attribute, use the :paramref:`.orm.defer.raiseload` parameter on the
    :func:`.defer` loader option.

    :param sql_only: if True, raise only if the lazy load would emit SQL,
     but not if it is only checking the identity map, or determining that
     the related value should just be None due to missing keys. When False,
     the strategy will raise for all varieties of relationship loading.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    .. seealso::

        :ref:`loading_toplevel`

        :ref:`prevent_lazy_with_raiseload`

        :ref:`orm_queryguide_deferred_raiseload`

    """

    return self._set_relationship_strategy(
        attr, {"lazy": "raise_on_sql" if sql_only else "raise"}
    )

defaultload

defaultload(attr: _AttrType) -> Self

Indicate an attribute should load using its predefined loader style.

The behavior of this loading option is to not change the current loading style of the attribute, meaning that the previously configured one is used or, if no previous style was selected, the default loading will be used.

This method is used to link to other loader options further into a chain of attributes without altering the loader style of the links along the chain. For example, to set joined eager loading for an element of an element::

session.query(MyClass).options(
    defaultload(MyClass.someattribute).
    joinedload(MyOtherClass.someotherattribute)
)

:func:.defaultload is also useful for setting column-level options on a related class, namely that of :func:.defer and :func:.undefer::

session.query(MyClass).options(
    defaultload(MyClass.someattribute).
    defer("some_column").
    undefer("some_other_column")
)

.. seealso::

:ref:`orm_queryguide_relationship_sub_options`

:meth:`_orm.Load.options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def defaultload(self, attr: _AttrType) -> Self:
    """Indicate an attribute should load using its predefined loader style.

    The behavior of this loading option is to not change the current
    loading style of the attribute, meaning that the previously configured
    one is used or, if no previous style was selected, the default
    loading will be used.

    This method is used to link to other loader options further into
    a chain of attributes without altering the loader style of the links
    along the chain.  For example, to set joined eager loading for an
    element of an element::

        session.query(MyClass).options(
            defaultload(MyClass.someattribute).
            joinedload(MyOtherClass.someotherattribute)
        )

    :func:`.defaultload` is also useful for setting column-level options on
    a related class, namely that of :func:`.defer` and :func:`.undefer`::

        session.query(MyClass).options(
            defaultload(MyClass.someattribute).
            defer("some_column").
            undefer("some_other_column")
        )

    .. seealso::

        :ref:`orm_queryguide_relationship_sub_options`

        :meth:`_orm.Load.options`

    """
    return self._set_relationship_strategy(attr, None)

defer

defer(key: _AttrType, raiseload: bool = False) -> Self

Indicate that the given column-oriented attribute should be deferred, e.g. not loaded until accessed.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

e.g.::

from sqlalchemy.orm import defer

session.query(MyClass).options(
    defer(MyClass.attribute_one),
    defer(MyClass.attribute_two)
)

To specify a deferred load of an attribute on a related class, the path can be specified one token at a time, specifying the loading style for each link along the chain. To leave the loading style for a link unchanged, use :func:_orm.defaultload::

session.query(MyClass).options(
    defaultload(MyClass.someattr).defer(RelatedClass.some_column)
)

Multiple deferral options related to a relationship can be bundled at once using :meth:_orm.Load.options::

session.query(MyClass).options(
    defaultload(MyClass.someattr).options(
        defer(RelatedClass.some_column),
        defer(RelatedClass.some_other_column),
        defer(RelatedClass.another_column)
    )
)

:param key: Attribute to be deferred.

:param raiseload: raise :class:.InvalidRequestError rather than lazy loading a value when the deferred attribute is accessed. Used to prevent unwanted SQL from being emitted.

.. versionadded:: 1.4

.. seealso::

:ref:`orm_queryguide_column_deferral` - in the
:ref:`queryguide_toplevel`

:func:`_orm.load_only`

:func:`_orm.undefer`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def defer(self, key: _AttrType, raiseload: bool = False) -> Self:
    r"""Indicate that the given column-oriented attribute should be
    deferred, e.g. not loaded until accessed.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    e.g.::

        from sqlalchemy.orm import defer

        session.query(MyClass).options(
            defer(MyClass.attribute_one),
            defer(MyClass.attribute_two)
        )

    To specify a deferred load of an attribute on a related class,
    the path can be specified one token at a time, specifying the loading
    style for each link along the chain.  To leave the loading style
    for a link unchanged, use :func:`_orm.defaultload`::

        session.query(MyClass).options(
            defaultload(MyClass.someattr).defer(RelatedClass.some_column)
        )

    Multiple deferral options related to a relationship can be bundled
    at once using :meth:`_orm.Load.options`::


        session.query(MyClass).options(
            defaultload(MyClass.someattr).options(
                defer(RelatedClass.some_column),
                defer(RelatedClass.some_other_column),
                defer(RelatedClass.another_column)
            )
        )

    :param key: Attribute to be deferred.

    :param raiseload: raise :class:`.InvalidRequestError` rather than
     lazy loading a value when the deferred attribute is accessed. Used
     to prevent unwanted SQL from being emitted.

    .. versionadded:: 1.4

    .. seealso::

        :ref:`orm_queryguide_column_deferral` - in the
        :ref:`queryguide_toplevel`

        :func:`_orm.load_only`

        :func:`_orm.undefer`

    """
    strategy = {"deferred": True, "instrument": True}
    if raiseload:
        strategy["raiseload"] = True
    return self._set_column_strategy((key,), strategy)

undefer

undefer(key: _AttrType) -> Self

Indicate that the given column-oriented attribute should be undeferred, e.g. specified within the SELECT statement of the entity as a whole.

The column being undeferred is typically set up on the mapping as a :func:.deferred attribute.

This function is part of the :class:_orm.Load interface and supports both method-chained and standalone operation.

Examples::

# undefer two columns
session.query(MyClass).options(
    undefer(MyClass.col1), undefer(MyClass.col2)
)

# undefer all columns specific to a single class using Load + *
session.query(MyClass, MyOtherClass).options(
    Load(MyClass).undefer("*"))

# undefer a column on a related object
session.query(MyClass).options(
    defaultload(MyClass.items).undefer(MyClass.text))

:param key: Attribute to be undeferred.

.. seealso::

:ref:`orm_queryguide_column_deferral` - in the
:ref:`queryguide_toplevel`

:func:`_orm.defer`

:func:`_orm.undefer_group`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def undefer(self, key: _AttrType) -> Self:
    r"""Indicate that the given column-oriented attribute should be
    undeferred, e.g. specified within the SELECT statement of the entity
    as a whole.

    The column being undeferred is typically set up on the mapping as a
    :func:`.deferred` attribute.

    This function is part of the :class:`_orm.Load` interface and supports
    both method-chained and standalone operation.

    Examples::

        # undefer two columns
        session.query(MyClass).options(
            undefer(MyClass.col1), undefer(MyClass.col2)
        )

        # undefer all columns specific to a single class using Load + *
        session.query(MyClass, MyOtherClass).options(
            Load(MyClass).undefer("*"))

        # undefer a column on a related object
        session.query(MyClass).options(
            defaultload(MyClass.items).undefer(MyClass.text))

    :param key: Attribute to be undeferred.

    .. seealso::

        :ref:`orm_queryguide_column_deferral` - in the
        :ref:`queryguide_toplevel`

        :func:`_orm.defer`

        :func:`_orm.undefer_group`

    """
    return self._set_column_strategy(
        (key,), {"deferred": False, "instrument": True}
    )

undefer_group

undefer_group(name: str) -> Self

Indicate that columns within the given deferred group name should be undeferred.

The columns being undeferred are set up on the mapping as :func:.deferred attributes and include a "group" name.

E.g::

session.query(MyClass).options(undefer_group("large_attrs"))

To undefer a group of attributes on a related entity, the path can be spelled out using relationship loader options, such as :func:_orm.defaultload::

session.query(MyClass).options(
    defaultload("someattr").undefer_group("large_attrs"))

.. seealso::

:ref:`orm_queryguide_column_deferral` - in the
:ref:`queryguide_toplevel`

:func:`_orm.defer`

:func:`_orm.undefer`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def undefer_group(self, name: str) -> Self:
    """Indicate that columns within the given deferred group name should be
    undeferred.

    The columns being undeferred are set up on the mapping as
    :func:`.deferred` attributes and include a "group" name.

    E.g::

        session.query(MyClass).options(undefer_group("large_attrs"))

    To undefer a group of attributes on a related entity, the path can be
    spelled out using relationship loader options, such as
    :func:`_orm.defaultload`::

        session.query(MyClass).options(
            defaultload("someattr").undefer_group("large_attrs"))

    .. seealso::

        :ref:`orm_queryguide_column_deferral` - in the
        :ref:`queryguide_toplevel`

        :func:`_orm.defer`

        :func:`_orm.undefer`

    """
    return self._set_column_strategy(
        (_WILDCARD_TOKEN,), None, {f"undefer_group_{name}": True}
    )

with_expression

with_expression(
    key: _AttrType,
    expression: _ColumnExpressionArgument[Any],
) -> Self

Apply an ad-hoc SQL expression to a "deferred expression" attribute.

This option is used in conjunction with the :func:_orm.query_expression mapper-level construct that indicates an attribute which should be the target of an ad-hoc SQL expression.

E.g.::

stmt = select(SomeClass).options(
    with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y)
)

.. versionadded:: 1.2

:param key: Attribute to be populated

:param expr: SQL expression to be applied to the attribute.

.. seealso::

:ref:`orm_queryguide_with_expression` - background and usage
examples
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def with_expression(
    self,
    key: _AttrType,
    expression: _ColumnExpressionArgument[Any],
) -> Self:
    r"""Apply an ad-hoc SQL expression to a "deferred expression"
    attribute.

    This option is used in conjunction with the
    :func:`_orm.query_expression` mapper-level construct that indicates an
    attribute which should be the target of an ad-hoc SQL expression.

    E.g.::

        stmt = select(SomeClass).options(
            with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y)
        )

    .. versionadded:: 1.2

    :param key: Attribute to be populated

    :param expr: SQL expression to be applied to the attribute.

    .. seealso::

        :ref:`orm_queryguide_with_expression` - background and usage
        examples

    """

    expression = _orm_full_deannotate(
        coercions.expect(roles.LabeledColumnExprRole, expression)
    )

    return self._set_column_strategy(
        (key,), {"query_expression": True}, extra_criteria=(expression,)
    )

selectin_polymorphic

selectin_polymorphic(classes: Iterable[Type[Any]]) -> Self

Indicate an eager load should take place for all attributes specific to a subclass.

This uses an additional SELECT with IN against all matched primary key values, and is the per-query analogue to the "selectin" setting on the :paramref:.mapper.polymorphic_load parameter.

.. versionadded:: 1.2

.. seealso::

:ref:`polymorphic_selectin`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
def selectin_polymorphic(self, classes: Iterable[Type[Any]]) -> Self:
    """Indicate an eager load should take place for all attributes
    specific to a subclass.

    This uses an additional SELECT with IN against all matched primary
    key values, and is the per-query analogue to the ``"selectin"``
    setting on the :paramref:`.mapper.polymorphic_load` parameter.

    .. versionadded:: 1.2

    .. seealso::

        :ref:`polymorphic_selectin`

    """
    self = self._set_class_strategy(
        {"selectinload_polymorphic": True},
        opts={
            "entities": tuple(
                sorted((inspect(cls) for cls in classes), key=id)
            )
        },
    )
    return self

options

options(*opts: _AbstractLoad) -> Self

Apply a series of options as sub-options to this :class:_orm.Load object.

E.g.::

query = session.query(Author)
query = query.options(
            joinedload(Author.book).options(
                load_only(Book.summary, Book.excerpt),
                joinedload(Book.citations).options(
                    joinedload(Citation.author)
                )
            )
        )

:param *opts: A series of loader option objects (ultimately :class:_orm.Load objects) which should be applied to the path specified by this :class:_orm.Load object.

.. versionadded:: 1.3.6

.. seealso::

:func:`.defaultload`

:ref:`orm_queryguide_relationship_sub_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@_generative
def options(self, *opts: _AbstractLoad) -> Self:
    r"""Apply a series of options as sub-options to this
    :class:`_orm.Load`
    object.

    E.g.::

        query = session.query(Author)
        query = query.options(
                    joinedload(Author.book).options(
                        load_only(Book.summary, Book.excerpt),
                        joinedload(Book.citations).options(
                            joinedload(Citation.author)
                        )
                    )
                )

    :param \*opts: A series of loader option objects (ultimately
     :class:`_orm.Load` objects) which should be applied to the path
     specified by this :class:`_orm.Load` object.

    .. versionadded:: 1.3.6

    .. seealso::

        :func:`.defaultload`

        :ref:`orm_queryguide_relationship_sub_options`

    """
    for opt in opts:
        try:
            opt._apply_to_parent(self)
        except AttributeError as ae:
            if not isinstance(opt, _AbstractLoad):
                raise sa_exc.ArgumentError(
                    f"Loader option {opt} is not compatible with the "
                    "Load.options() method."
                ) from ae
            else:
                raise
    return self

Mapped

Bases: SQLORMExpression[_T_co], ORMDescriptor[_T_co], _MappedAnnotationBase[_T_co], DDLConstraintColumnRole

Represent an ORM mapped attribute on a mapped class.

This class represents the complete descriptor interface for any class attribute that will have been :term:instrumented by the ORM :class:_orm.Mapper class. Provides appropriate information to type checkers such as pylance and mypy so that ORM-mapped attributes are correctly typed.

The most prominent use of :class:_orm.Mapped is in the :ref:Declarative Mapping <orm_explicit_declarative_base> form of :class:_orm.Mapper configuration, where used explicitly it drives the configuration of ORM attributes such as :func:_orm.mapped_class and :func:_orm.relationship.

.. seealso::

:ref:`orm_explicit_declarative_base`

:ref:`orm_declarative_table`

.. tip::

The :class:`_orm.Mapped` class represents attributes that are handled
directly by the :class:`_orm.Mapper` class. It does not include other
Python descriptor classes that are provided as extensions, including
:ref:`hybrids_toplevel` and the :ref:`associationproxy_toplevel`.
While these systems still make use of ORM-specific superclasses
and structures, they are not :term:`instrumented` by the
:class:`_orm.Mapper` and instead provide their own functionality
when they are accessed on a class.

.. versionadded:: 1.4

timetuple class-attribute instance-attribute

timetuple: Literal[None] = None

Hack, allows datetime objects to be compared on the LHS.

Mapper

Mapper(
    class_: Type[_O],
    local_table: Optional[FromClause] = None,
    properties: Optional[
        Mapping[str, MapperProperty[Any]]
    ] = None,
    primary_key: Optional[
        Iterable[_ORMColumnExprArgument[Any]]
    ] = None,
    non_primary: bool = False,
    inherits: Optional[
        Union[Mapper[Any], Type[Any]]
    ] = None,
    inherit_condition: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    inherit_foreign_keys: Optional[
        Sequence[_ORMColumnExprArgument[Any]]
    ] = None,
    always_refresh: bool = False,
    version_id_col: Optional[
        _ORMColumnExprArgument[Any]
    ] = None,
    version_id_generator: Optional[
        Union[Literal[False], Callable[[Any], Any]]
    ] = None,
    polymorphic_on: Optional[
        Union[
            _ORMColumnExprArgument[Any],
            str,
            MapperProperty[Any],
        ]
    ] = None,
    _polymorphic_map: Optional[
        Dict[Any, Mapper[Any]]
    ] = None,
    polymorphic_identity: Optional[Any] = None,
    concrete: bool = False,
    with_polymorphic: Optional[_WithPolymorphicArg] = None,
    polymorphic_abstract: bool = False,
    polymorphic_load: Optional[
        Literal["selectin", "inline"]
    ] = None,
    allow_partial_pks: bool = True,
    batch: bool = True,
    column_prefix: Optional[str] = None,
    include_properties: Optional[Sequence[str]] = None,
    exclude_properties: Optional[Sequence[str]] = None,
    passive_updates: bool = True,
    passive_deletes: bool = False,
    confirm_deleted_rows: bool = True,
    eager_defaults: Literal[True, False, "auto"] = "auto",
    legacy_is_orphan: bool = False,
    _compiled_cache_size: int = 100,
)

Bases: ORMFromClauseRole, ORMEntityColumnsClauseRole[_O], MemoizedHasCacheKey, InspectionAttr, Identified, Inspectable['Mapper[_O]'], EventTarget, Generic[_O]

Defines an association between a Python class and a database table or other relational structure, so that ORM operations against the class may proceed.

The :class:_orm.Mapper object is instantiated using mapping methods present on the :class:_orm.registry object. For information about instantiating new :class:_orm.Mapper objects, see :ref:orm_mapping_classes_toplevel.

Direct constructor for a new :class:_orm.Mapper object.

The :class:_orm.Mapper constructor is not called directly, and is normally invoked through the use of the :class:_orm.registry object through either the :ref:Declarative <orm_declarative_mapping> or :ref:Imperative <orm_imperative_mapping> mapping styles.

.. versionchanged:: 2.0 The public facing mapper() function is removed; for a classical mapping configuration, use the :meth:_orm.registry.map_imperatively method.

Parameters documented below may be passed to either the :meth:_orm.registry.map_imperatively method, or may be passed in the __mapper_args__ declarative class attribute described at :ref:orm_declarative_mapper_options.

:param class_: The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself.

:param local_table: The :class:_schema.Table or other :class:_sql.FromClause (i.e. selectable) to which the class is mapped. May be None if this mapper inherits from another mapper using single-table inheritance. When using Declarative, this argument is automatically passed by the extension, based on what is configured via the :attr:_orm.DeclarativeBase.__table__ attribute or via the :class:_schema.Table produced as a result of the :attr:_orm.DeclarativeBase.__tablename__ attribute being present.

:param polymorphic_abstract: Indicates this class will be mapped in a polymorphic hierarchy, but not directly instantiated. The class is mapped normally, except that it has no requirement for a :paramref:_orm.Mapper.polymorphic_identity within an inheritance hierarchy. The class however must be part of a polymorphic inheritance scheme which uses :paramref:_orm.Mapper.polymorphic_on at the base.

.. versionadded:: 2.0

.. seealso::

    :ref:`orm_inheritance_abstract_poly`

:param always_refresh: If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method :meth:_query.Query.populate_existing.

:param allow_partial_pks: Defaults to True. Indicates that a composite primary key with some NULL values should be considered as possibly existing within the database. This affects whether a mapper will assign an incoming row to an existing identity, as well as if :meth:.Session.merge will check the database first for a particular primary key value. A "partial primary key" can occur if one has mapped to an OUTER JOIN, for example.

:param batch: Defaults to True, indicating that save operations of multiple entities can be batched together for efficiency. Setting to False indicates that an instance will be fully saved before saving the next instance. This is used in the extremely rare case that a :class:.MapperEvents listener requires being called in between individual row persistence operations.

:param column_prefix: A string which will be prepended to the mapped attribute name when :class:_schema.Column objects are automatically assigned as attributes to the mapped class. Does not affect :class:.Column objects that are mapped explicitly in the :paramref:.Mapper.properties dictionary.

This parameter is typically useful with imperative mappings that keep the :class:.Table object separate. Below, assuming the user_table :class:.Table object has columns named user_id, user_name, and password::

    class User(Base):
        __table__ = user_table
        __mapper_args__ = {'column_prefix':'_'}

The above mapping will assign the user_id, user_name, and password columns to attributes named _user_id, _user_name, and _password on the mapped User class.

The :paramref:.Mapper.column_prefix parameter is uncommon in modern use. For dealing with reflected tables, a more flexible approach to automating a naming scheme is to intercept the :class:.Column objects as they are reflected; see the section :ref:mapper_automated_reflection_schemes for notes on this usage pattern.

:param concrete: If True, indicates this mapper should use concrete table inheritance with its parent mapper.

See the section :ref:concrete_inheritance for an example.

:param confirm_deleted_rows: defaults to True; when a DELETE occurs of one more rows based on specific primary keys, a warning is emitted when the number of rows matched does not equal the number of rows expected. This parameter may be set to False to handle the case where database ON DELETE CASCADE rules may be deleting some of those rows automatically. The warning may be changed to an exception in a future release.

:param eager_defaults: if True, the ORM will immediately fetch the value of server-generated default values after an INSERT or UPDATE, rather than leaving them as expired to be fetched on next access. This can be used for event schemes where the server-generated values are needed immediately before the flush completes.

The fetch of values occurs either by using RETURNING inline with the INSERT or UPDATE statement, or by adding an additional SELECT statement subsequent to the INSERT or UPDATE, if the backend does not support RETURNING.

The use of RETURNING is extremely performant in particular for INSERT statements where SQLAlchemy can take advantage of :ref:insertmanyvalues <engine_insertmanyvalues>, whereas the use of an additional SELECT is relatively poor performing, adding additional SQL round trips which would be unnecessary if these new attributes are not to be accessed in any case.

For this reason, :paramref:.Mapper.eager_defaults defaults to the string value "auto", which indicates that server defaults for INSERT should be fetched using RETURNING if the backing database supports it and if the dialect in use supports "insertmanyreturning" for an INSERT statement. If the backing database does not support RETURNING or "insertmanyreturning" is not available, server defaults will not be fetched.

.. versionchanged:: 2.0.0rc1 added the "auto" option for :paramref:.Mapper.eager_defaults

.. seealso::

    :ref:`orm_server_defaults`

.. versionchanged:: 2.0.0 RETURNING now works with multiple rows INSERTed at once using the :ref:insertmanyvalues <engine_insertmanyvalues> feature, which among other things allows the :paramref:.Mapper.eager_defaults feature to be very performant on supporting backends.

:param exclude_properties: A list or set of string column names to be excluded from mapping.

.. seealso::

:ref:`include_exclude_cols`

:param include_properties: An inclusive list or set of string column names to map.

.. seealso::

:ref:`include_exclude_cols`

:param inherits: A mapped class or the corresponding :class:_orm.Mapper of one indicating a superclass to which this :class:_orm.Mapper should inherit from. The mapped class here must be a subclass of the other mapper's class. When using Declarative, this argument is passed automatically as a result of the natural class hierarchy of the declared classes.

.. seealso::

:ref:`inheritance_toplevel`

:param inherit_condition: For joined table inheritance, a SQL expression which will define how the two tables are joined; defaults to a natural join between the two tables.

:param inherit_foreign_keys: When inherit_condition is used and the columns present are missing a :class:_schema.ForeignKey configuration, this parameter can be used to specify which columns are "foreign". In most cases can be left as None.

:param legacy_is_orphan: Boolean, defaults to False. When True, specifies that "legacy" orphan consideration is to be applied to objects mapped by this mapper, which means that a pending (that is, not persistent) object is auto-expunged from an owning :class:.Session only when it is de-associated from all parents that specify a delete-orphan cascade towards this mapper. The new default behavior is that the object is auto-expunged when it is de-associated with any of its parents that specify delete-orphan cascade. This behavior is more consistent with that of a persistent object, and allows behavior to be consistent in more scenarios independently of whether or not an orphan object has been flushed yet or not.

See the change note and example at :ref:legacy_is_orphan_addition for more detail on this change.

:param non_primary: Specify that this :class:_orm.Mapper is in addition to the "primary" mapper, that is, the one used for persistence. The :class:_orm.Mapper created here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only.

.. seealso::

:ref:`relationship_aliased_class` - the new pattern that removes
the need for the :paramref:`_orm.Mapper.non_primary` flag.

:param passive_deletes: Indicates DELETE behavior of foreign key columns when a joined-table inheritance entity is being deleted. Defaults to False for a base mapper; for an inheriting mapper, defaults to False unless the value is set to True on the superclass mapper.

When True, it is assumed that ON DELETE CASCADE is configured on the foreign key relationships that link this mapper's table to its superclass table, so that when the unit of work attempts to delete the entity, it need only emit a DELETE statement for the superclass table, and not this table.

When False, a DELETE statement is emitted for this mapper's table individually. If the primary key attributes local to this table are unloaded, then a SELECT must be emitted in order to validate these attributes; note that the primary key columns of a joined-table subclass are not part of the "primary key" of the object as a whole.

Note that a value of True is always forced onto the subclass mappers; that is, it's not possible for a superclass to specify passive_deletes without this taking effect for all subclass mappers.

.. seealso::

   :ref:`passive_deletes` - description of similar feature as
   used with :func:`_orm.relationship`

   :paramref:`.mapper.passive_updates` - supporting ON UPDATE
   CASCADE for joined-table inheritance mappers

:param passive_updates: Indicates UPDATE behavior of foreign key columns when a primary key column changes on a joined-table inheritance mapping. Defaults to True.

When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent columns on joined-table rows.

When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The unit of work process will emit an UPDATE statement for the dependent columns during a primary key change.

.. seealso::

   :ref:`passive_updates` - description of a similar feature as
   used with :func:`_orm.relationship`

   :paramref:`.mapper.passive_deletes` - supporting ON DELETE
   CASCADE for joined-table inheritance mappers

:param polymorphic_load: Specifies "polymorphic loading" behavior for a subclass in an inheritance hierarchy (joined and single table inheritance only). Valid values are:

  • "'inline'" - specifies this class should be part of the "with_polymorphic" mappers, e.g. its columns will be included in a SELECT query against the base.

  • "'selectin'" - specifies that when instances of this class are loaded, an additional SELECT will be emitted to retrieve the columns specific to this subclass. The SELECT uses IN to fetch multiple subclasses at once.

.. versionadded:: 1.2

.. seealso::

:ref:`with_polymorphic_mapper_config`

:ref:`polymorphic_selectin`

:param polymorphic_on: Specifies the column, attribute, or SQL expression used to determine the target class for an incoming row, when inheriting classes are present.

May be specified as a string attribute name, or as a SQL expression such as a :class:_schema.Column or in a Declarative mapping a :func:_orm.mapped_column object. It is typically expected that the SQL expression corresponds to a column in the base-most mapped :class:.Table::

class Employee(Base):
    __tablename__ = 'employee'

    id: Mapped[int] = mapped_column(primary_key=True)
    discriminator: Mapped[str] = mapped_column(String(50))

    __mapper_args__ = {
        "polymorphic_on":discriminator,
        "polymorphic_identity":"employee"
    }

It may also be specified as a SQL expression, as in this example where we use the :func:.case construct to provide a conditional approach::

class Employee(Base):
    __tablename__ = 'employee'

    id: Mapped[int] = mapped_column(primary_key=True)
    discriminator: Mapped[str] = mapped_column(String(50))

    __mapper_args__ = {
        "polymorphic_on":case(
            (discriminator == "EN", "engineer"),
            (discriminator == "MA", "manager"),
            else_="employee"),
        "polymorphic_identity":"employee"
    }

It may also refer to any attribute using its string name, which is of particular use when using annotated column configurations::

    class Employee(Base):
        __tablename__ = 'employee'

        id: Mapped[int] = mapped_column(primary_key=True)
        discriminator: Mapped[str]

        __mapper_args__ = {
            "polymorphic_on": "discriminator",
            "polymorphic_identity": "employee"
        }

When setting polymorphic_on to reference an attribute or expression that's not present in the locally mapped :class:_schema.Table, yet the value of the discriminator should be persisted to the database, the value of the discriminator is not automatically set on new instances; this must be handled by the user, either through manual means or via event listeners. A typical approach to establishing such a listener looks like::

    from sqlalchemy import event
    from sqlalchemy.orm import object_mapper

    @event.listens_for(Employee, "init", propagate=True)
    def set_identity(instance, *arg, **kw):
        mapper = object_mapper(instance)
        instance.discriminator = mapper.polymorphic_identity

Where above, we assign the value of polymorphic_identity for the mapped class to the discriminator attribute, thus persisting the value to the discriminator column in the database.

.. warning::

 Currently, **only one discriminator column may be set**, typically
 on the base-most class in the hierarchy. "Cascading" polymorphic
 columns are not yet supported.

.. seealso::

:ref:`inheritance_toplevel`

:param polymorphic_identity: Specifies the value which identifies this particular class as returned by the column expression referred to by the :paramref:_orm.Mapper.polymorphic_on setting. As rows are received, the value corresponding to the :paramref:_orm.Mapper.polymorphic_on column expression is compared to this value, indicating which subclass should be used for the newly reconstructed object.

.. seealso::

:ref:`inheritance_toplevel`

:param properties: A dictionary mapping the string names of object attributes to :class:.MapperProperty instances, which define the persistence behavior of that attribute. Note that :class:_schema.Column objects present in the mapped :class:_schema.Table are automatically placed into ColumnProperty instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those :class:.MapperProperty instances declared in the declared class body.

.. seealso::

   :ref:`orm_mapping_properties` - in the
   :ref:`orm_mapping_classes_toplevel`

:param primary_key: A list of :class:_schema.Column objects, or alternatively string names of attribute names which refer to :class:_schema.Column, which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.

.. versionchanged:: 2.0.2 :paramref:_orm.Mapper.primary_key arguments may be indicated as string attribute names as well.

.. seealso::

    :ref:`mapper_primary_key` - background and example use

:param version_id_col: A :class:_schema.Column that will be used to keep a running version id of rows in the table. This is used to detect concurrent updates or the presence of stale data in a flush. The methodology is to detect if an UPDATE statement does not match the last known version id, a :class:~sqlalchemy.orm.exc.StaleDataError exception is thrown. By default, the column must be of :class:.Integer type, unless version_id_generator specifies an alternative version generator.

.. seealso::

  :ref:`mapper_version_counter` - discussion of version counting
  and rationale.

:param version_id_generator: Define how new version ids should be generated. Defaults to None, which indicates that a simple integer counting scheme be employed. To provide a custom versioning scheme, provide a callable function of the form::

  def generate_version(version):
      return next_version

Alternatively, server-side versioning functions such as triggers, or programmatic versioning schemes outside of the version id generator may be used, by specifying the value False. Please see :ref:server_side_version_counter for a discussion of important points when using this option.

.. seealso::

 :ref:`custom_version_counter`

 :ref:`server_side_version_counter`

:param with_polymorphic: A tuple in the form (<classes>, <selectable>) indicating the default style of "polymorphic" loading, that is, which tables are queried at once. is any single or list of mappers and/or classes indicating the inherited classes that should be loaded at once. The special value '*' may be used to indicate all descending classes should be loaded immediately. The second tuple argument indicates a selectable that will be used to query for multiple classes.

The :paramref:`_orm.Mapper.polymorphic_load` parameter may be
preferable over the use of :paramref:`_orm.Mapper.with_polymorphic`
in modern mappings to indicate a per-subclass technique of
indicating polymorphic loading styles.

.. seealso::

    :ref:`with_polymorphic_mapper_config`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
@util.deprecated_params(
    non_primary=(
        "1.3",
        "The :paramref:`.mapper.non_primary` parameter is deprecated, "
        "and will be removed in a future release.  The functionality "
        "of non primary mappers is now better suited using the "
        ":class:`.AliasedClass` construct, which can also be used "
        "as the target of a :func:`_orm.relationship` in 1.3.",
    ),
)
def __init__(
    self,
    class_: Type[_O],
    local_table: Optional[FromClause] = None,
    properties: Optional[Mapping[str, MapperProperty[Any]]] = None,
    primary_key: Optional[Iterable[_ORMColumnExprArgument[Any]]] = None,
    non_primary: bool = False,
    inherits: Optional[Union[Mapper[Any], Type[Any]]] = None,
    inherit_condition: Optional[_ColumnExpressionArgument[bool]] = None,
    inherit_foreign_keys: Optional[
        Sequence[_ORMColumnExprArgument[Any]]
    ] = None,
    always_refresh: bool = False,
    version_id_col: Optional[_ORMColumnExprArgument[Any]] = None,
    version_id_generator: Optional[
        Union[Literal[False], Callable[[Any], Any]]
    ] = None,
    polymorphic_on: Optional[
        Union[_ORMColumnExprArgument[Any], str, MapperProperty[Any]]
    ] = None,
    _polymorphic_map: Optional[Dict[Any, Mapper[Any]]] = None,
    polymorphic_identity: Optional[Any] = None,
    concrete: bool = False,
    with_polymorphic: Optional[_WithPolymorphicArg] = None,
    polymorphic_abstract: bool = False,
    polymorphic_load: Optional[Literal["selectin", "inline"]] = None,
    allow_partial_pks: bool = True,
    batch: bool = True,
    column_prefix: Optional[str] = None,
    include_properties: Optional[Sequence[str]] = None,
    exclude_properties: Optional[Sequence[str]] = None,
    passive_updates: bool = True,
    passive_deletes: bool = False,
    confirm_deleted_rows: bool = True,
    eager_defaults: Literal[True, False, "auto"] = "auto",
    legacy_is_orphan: bool = False,
    _compiled_cache_size: int = 100,
):
    r"""Direct constructor for a new :class:`_orm.Mapper` object.

    The :class:`_orm.Mapper` constructor is not called directly, and
    is normally invoked through the
    use of the :class:`_orm.registry` object through either the
    :ref:`Declarative <orm_declarative_mapping>` or
    :ref:`Imperative <orm_imperative_mapping>` mapping styles.

    .. versionchanged:: 2.0 The public facing ``mapper()`` function is
       removed; for a classical mapping configuration, use the
       :meth:`_orm.registry.map_imperatively` method.

    Parameters documented below may be passed to either the
    :meth:`_orm.registry.map_imperatively` method, or may be passed in the
    ``__mapper_args__`` declarative class attribute described at
    :ref:`orm_declarative_mapper_options`.

    :param class\_: The class to be mapped.  When using Declarative,
      this argument is automatically passed as the declared class
      itself.

    :param local_table: The :class:`_schema.Table` or other
       :class:`_sql.FromClause` (i.e. selectable) to which the class is
       mapped. May be ``None`` if this mapper inherits from another mapper
       using single-table inheritance. When using Declarative, this
       argument is automatically passed by the extension, based on what is
       configured via the :attr:`_orm.DeclarativeBase.__table__` attribute
       or via the :class:`_schema.Table` produced as a result of
       the :attr:`_orm.DeclarativeBase.__tablename__` attribute being
       present.

    :param polymorphic_abstract: Indicates this class will be mapped in a
        polymorphic hierarchy, but not directly instantiated. The class is
        mapped normally, except that it has no requirement for a
        :paramref:`_orm.Mapper.polymorphic_identity` within an inheritance
        hierarchy. The class however must be part of a polymorphic
        inheritance scheme which uses
        :paramref:`_orm.Mapper.polymorphic_on` at the base.

        .. versionadded:: 2.0

        .. seealso::

            :ref:`orm_inheritance_abstract_poly`

    :param always_refresh: If True, all query operations for this mapped
       class will overwrite all data within object instances that already
       exist within the session, erasing any in-memory changes with
       whatever information was loaded from the database. Usage of this
       flag is highly discouraged; as an alternative, see the method
       :meth:`_query.Query.populate_existing`.

    :param allow_partial_pks: Defaults to True.  Indicates that a
       composite primary key with some NULL values should be considered as
       possibly existing within the database. This affects whether a
       mapper will assign an incoming row to an existing identity, as well
       as if :meth:`.Session.merge` will check the database first for a
       particular primary key value. A "partial primary key" can occur if
       one has mapped to an OUTER JOIN, for example.

    :param batch: Defaults to ``True``, indicating that save operations
       of multiple entities can be batched together for efficiency.
       Setting to False indicates
       that an instance will be fully saved before saving the next
       instance.  This is used in the extremely rare case that a
       :class:`.MapperEvents` listener requires being called
       in between individual row persistence operations.

    :param column_prefix: A string which will be prepended
       to the mapped attribute name when :class:`_schema.Column`
       objects are automatically assigned as attributes to the
       mapped class.  Does not affect :class:`.Column` objects that
       are mapped explicitly in the :paramref:`.Mapper.properties`
       dictionary.

       This parameter is typically useful with imperative mappings
       that keep the :class:`.Table` object separate.  Below, assuming
       the ``user_table`` :class:`.Table` object has columns named
       ``user_id``, ``user_name``, and ``password``::

            class User(Base):
                __table__ = user_table
                __mapper_args__ = {'column_prefix':'_'}

       The above mapping will assign the ``user_id``, ``user_name``, and
       ``password`` columns to attributes named ``_user_id``,
       ``_user_name``, and ``_password`` on the mapped ``User`` class.

       The :paramref:`.Mapper.column_prefix` parameter is uncommon in
       modern use. For dealing with reflected tables, a more flexible
       approach to automating a naming scheme is to intercept the
       :class:`.Column` objects as they are reflected; see the section
       :ref:`mapper_automated_reflection_schemes` for notes on this usage
       pattern.

    :param concrete: If True, indicates this mapper should use concrete
       table inheritance with its parent mapper.

       See the section :ref:`concrete_inheritance` for an example.

    :param confirm_deleted_rows: defaults to True; when a DELETE occurs
      of one more rows based on specific primary keys, a warning is
      emitted when the number of rows matched does not equal the number
      of rows expected.  This parameter may be set to False to handle the
      case where database ON DELETE CASCADE rules may be deleting some of
      those rows automatically.  The warning may be changed to an
      exception in a future release.

    :param eager_defaults: if True, the ORM will immediately fetch the
      value of server-generated default values after an INSERT or UPDATE,
      rather than leaving them as expired to be fetched on next access.
      This can be used for event schemes where the server-generated values
      are needed immediately before the flush completes.

      The fetch of values occurs either by using ``RETURNING`` inline
      with the ``INSERT`` or ``UPDATE`` statement, or by adding an
      additional ``SELECT`` statement subsequent to the ``INSERT`` or
      ``UPDATE``, if the backend does not support ``RETURNING``.

      The use of ``RETURNING`` is extremely performant in particular for
      ``INSERT`` statements where SQLAlchemy can take advantage of
      :ref:`insertmanyvalues <engine_insertmanyvalues>`, whereas the use of
      an additional ``SELECT`` is relatively poor performing, adding
      additional SQL round trips which would be unnecessary if these new
      attributes are not to be accessed in any case.

      For this reason, :paramref:`.Mapper.eager_defaults` defaults to the
      string value ``"auto"``, which indicates that server defaults for
      INSERT should be fetched using ``RETURNING`` if the backing database
      supports it and if the dialect in use supports "insertmanyreturning"
      for an INSERT statement. If the backing database does not support
      ``RETURNING`` or "insertmanyreturning" is not available, server
      defaults will not be fetched.

      .. versionchanged:: 2.0.0rc1 added the "auto" option for
         :paramref:`.Mapper.eager_defaults`

      .. seealso::

            :ref:`orm_server_defaults`

      .. versionchanged:: 2.0.0  RETURNING now works with multiple rows
         INSERTed at once using the
         :ref:`insertmanyvalues <engine_insertmanyvalues>` feature, which
         among other things allows the :paramref:`.Mapper.eager_defaults`
         feature to be very performant on supporting backends.

    :param exclude_properties: A list or set of string column names to
      be excluded from mapping.

      .. seealso::

        :ref:`include_exclude_cols`

    :param include_properties: An inclusive list or set of string column
      names to map.

      .. seealso::

        :ref:`include_exclude_cols`

    :param inherits: A mapped class or the corresponding
      :class:`_orm.Mapper`
      of one indicating a superclass to which this :class:`_orm.Mapper`
      should *inherit* from.   The mapped class here must be a subclass
      of the other mapper's class.   When using Declarative, this argument
      is passed automatically as a result of the natural class
      hierarchy of the declared classes.

      .. seealso::

        :ref:`inheritance_toplevel`

    :param inherit_condition: For joined table inheritance, a SQL
       expression which will
       define how the two tables are joined; defaults to a natural join
       between the two tables.

    :param inherit_foreign_keys: When ``inherit_condition`` is used and
       the columns present are missing a :class:`_schema.ForeignKey`
       configuration, this parameter can be used to specify which columns
       are "foreign".  In most cases can be left as ``None``.

    :param legacy_is_orphan: Boolean, defaults to ``False``.
      When ``True``, specifies that "legacy" orphan consideration
      is to be applied to objects mapped by this mapper, which means
      that a pending (that is, not persistent) object is auto-expunged
      from an owning :class:`.Session` only when it is de-associated
      from *all* parents that specify a ``delete-orphan`` cascade towards
      this mapper.  The new default behavior is that the object is
      auto-expunged when it is de-associated with *any* of its parents
      that specify ``delete-orphan`` cascade.  This behavior is more
      consistent with that of a persistent object, and allows behavior to
      be consistent in more scenarios independently of whether or not an
      orphan object has been flushed yet or not.

      See the change note and example at :ref:`legacy_is_orphan_addition`
      for more detail on this change.

    :param non_primary: Specify that this :class:`_orm.Mapper`
      is in addition
      to the "primary" mapper, that is, the one used for persistence.
      The :class:`_orm.Mapper` created here may be used for ad-hoc
      mapping of the class to an alternate selectable, for loading
      only.

     .. seealso::

        :ref:`relationship_aliased_class` - the new pattern that removes
        the need for the :paramref:`_orm.Mapper.non_primary` flag.

    :param passive_deletes: Indicates DELETE behavior of foreign key
       columns when a joined-table inheritance entity is being deleted.
       Defaults to ``False`` for a base mapper; for an inheriting mapper,
       defaults to ``False`` unless the value is set to ``True``
       on the superclass mapper.

       When ``True``, it is assumed that ON DELETE CASCADE is configured
       on the foreign key relationships that link this mapper's table
       to its superclass table, so that when the unit of work attempts
       to delete the entity, it need only emit a DELETE statement for the
       superclass table, and not this table.

       When ``False``, a DELETE statement is emitted for this mapper's
       table individually.  If the primary key attributes local to this
       table are unloaded, then a SELECT must be emitted in order to
       validate these attributes; note that the primary key columns
       of a joined-table subclass are not part of the "primary key" of
       the object as a whole.

       Note that a value of ``True`` is **always** forced onto the
       subclass mappers; that is, it's not possible for a superclass
       to specify passive_deletes without this taking effect for
       all subclass mappers.

       .. seealso::

           :ref:`passive_deletes` - description of similar feature as
           used with :func:`_orm.relationship`

           :paramref:`.mapper.passive_updates` - supporting ON UPDATE
           CASCADE for joined-table inheritance mappers

    :param passive_updates: Indicates UPDATE behavior of foreign key
       columns when a primary key column changes on a joined-table
       inheritance mapping.   Defaults to ``True``.

       When True, it is assumed that ON UPDATE CASCADE is configured on
       the foreign key in the database, and that the database will handle
       propagation of an UPDATE from a source column to dependent columns
       on joined-table rows.

       When False, it is assumed that the database does not enforce
       referential integrity and will not be issuing its own CASCADE
       operation for an update.  The unit of work process will
       emit an UPDATE statement for the dependent columns during a
       primary key change.

       .. seealso::

           :ref:`passive_updates` - description of a similar feature as
           used with :func:`_orm.relationship`

           :paramref:`.mapper.passive_deletes` - supporting ON DELETE
           CASCADE for joined-table inheritance mappers

    :param polymorphic_load: Specifies "polymorphic loading" behavior
     for a subclass in an inheritance hierarchy (joined and single
     table inheritance only).   Valid values are:

      * "'inline'" - specifies this class should be part of
        the "with_polymorphic" mappers, e.g. its columns will be included
        in a SELECT query against the base.

      * "'selectin'" - specifies that when instances of this class
        are loaded, an additional SELECT will be emitted to retrieve
        the columns specific to this subclass.  The SELECT uses
        IN to fetch multiple subclasses at once.

     .. versionadded:: 1.2

     .. seealso::

        :ref:`with_polymorphic_mapper_config`

        :ref:`polymorphic_selectin`

    :param polymorphic_on: Specifies the column, attribute, or
      SQL expression used to determine the target class for an
      incoming row, when inheriting classes are present.

      May be specified as a string attribute name, or as a SQL
      expression such as a :class:`_schema.Column` or in a Declarative
      mapping a :func:`_orm.mapped_column` object.  It is typically
      expected that the SQL expression corresponds to a column in the
      base-most mapped :class:`.Table`::

        class Employee(Base):
            __tablename__ = 'employee'

            id: Mapped[int] = mapped_column(primary_key=True)
            discriminator: Mapped[str] = mapped_column(String(50))

            __mapper_args__ = {
                "polymorphic_on":discriminator,
                "polymorphic_identity":"employee"
            }

      It may also be specified
      as a SQL expression, as in this example where we
      use the :func:`.case` construct to provide a conditional
      approach::

        class Employee(Base):
            __tablename__ = 'employee'

            id: Mapped[int] = mapped_column(primary_key=True)
            discriminator: Mapped[str] = mapped_column(String(50))

            __mapper_args__ = {
                "polymorphic_on":case(
                    (discriminator == "EN", "engineer"),
                    (discriminator == "MA", "manager"),
                    else_="employee"),
                "polymorphic_identity":"employee"
            }

      It may also refer to any attribute using its string name,
      which is of particular use when using annotated column
      configurations::

            class Employee(Base):
                __tablename__ = 'employee'

                id: Mapped[int] = mapped_column(primary_key=True)
                discriminator: Mapped[str]

                __mapper_args__ = {
                    "polymorphic_on": "discriminator",
                    "polymorphic_identity": "employee"
                }

      When setting ``polymorphic_on`` to reference an
      attribute or expression that's not present in the
      locally mapped :class:`_schema.Table`, yet the value
      of the discriminator should be persisted to the database,
      the value of the
      discriminator is not automatically set on new
      instances; this must be handled by the user,
      either through manual means or via event listeners.
      A typical approach to establishing such a listener
      looks like::

            from sqlalchemy import event
            from sqlalchemy.orm import object_mapper

            @event.listens_for(Employee, "init", propagate=True)
            def set_identity(instance, *arg, **kw):
                mapper = object_mapper(instance)
                instance.discriminator = mapper.polymorphic_identity

      Where above, we assign the value of ``polymorphic_identity``
      for the mapped class to the ``discriminator`` attribute,
      thus persisting the value to the ``discriminator`` column
      in the database.

      .. warning::

         Currently, **only one discriminator column may be set**, typically
         on the base-most class in the hierarchy. "Cascading" polymorphic
         columns are not yet supported.

      .. seealso::

        :ref:`inheritance_toplevel`

    :param polymorphic_identity: Specifies the value which
      identifies this particular class as returned by the column expression
      referred to by the :paramref:`_orm.Mapper.polymorphic_on` setting. As
      rows are received, the value corresponding to the
      :paramref:`_orm.Mapper.polymorphic_on` column expression is compared
      to this value, indicating which subclass should be used for the newly
      reconstructed object.

      .. seealso::

        :ref:`inheritance_toplevel`

    :param properties: A dictionary mapping the string names of object
       attributes to :class:`.MapperProperty` instances, which define the
       persistence behavior of that attribute.  Note that
       :class:`_schema.Column`
       objects present in
       the mapped :class:`_schema.Table` are automatically placed into
       ``ColumnProperty`` instances upon mapping, unless overridden.
       When using Declarative, this argument is passed automatically,
       based on all those :class:`.MapperProperty` instances declared
       in the declared class body.

       .. seealso::

           :ref:`orm_mapping_properties` - in the
           :ref:`orm_mapping_classes_toplevel`

    :param primary_key: A list of :class:`_schema.Column`
       objects, or alternatively string names of attribute names which
       refer to :class:`_schema.Column`, which define
       the primary key to be used against this mapper's selectable unit.
       This is normally simply the primary key of the ``local_table``, but
       can be overridden here.

       .. versionchanged:: 2.0.2 :paramref:`_orm.Mapper.primary_key`
          arguments may be indicated as string attribute names as well.

       .. seealso::

            :ref:`mapper_primary_key` - background and example use

    :param version_id_col: A :class:`_schema.Column`
       that will be used to keep a running version id of rows
       in the table.  This is used to detect concurrent updates or
       the presence of stale data in a flush.  The methodology is to
       detect if an UPDATE statement does not match the last known
       version id, a
       :class:`~sqlalchemy.orm.exc.StaleDataError` exception is
       thrown.
       By default, the column must be of :class:`.Integer` type,
       unless ``version_id_generator`` specifies an alternative version
       generator.

       .. seealso::

          :ref:`mapper_version_counter` - discussion of version counting
          and rationale.

    :param version_id_generator: Define how new version ids should
      be generated.  Defaults to ``None``, which indicates that
      a simple integer counting scheme be employed.  To provide a custom
      versioning scheme, provide a callable function of the form::

          def generate_version(version):
              return next_version

      Alternatively, server-side versioning functions such as triggers,
      or programmatic versioning schemes outside of the version id
      generator may be used, by specifying the value ``False``.
      Please see :ref:`server_side_version_counter` for a discussion
      of important points when using this option.

      .. seealso::

         :ref:`custom_version_counter`

         :ref:`server_side_version_counter`


    :param with_polymorphic: A tuple in the form ``(<classes>,
        <selectable>)`` indicating the default style of "polymorphic"
        loading, that is, which tables are queried at once. <classes> is
        any single or list of mappers and/or classes indicating the
        inherited classes that should be loaded at once. The special value
        ``'*'`` may be used to indicate all descending classes should be
        loaded immediately. The second tuple argument <selectable>
        indicates a selectable that will be used to query for multiple
        classes.

        The :paramref:`_orm.Mapper.polymorphic_load` parameter may be
        preferable over the use of :paramref:`_orm.Mapper.with_polymorphic`
        in modern mappings to indicate a per-subclass technique of
        indicating polymorphic loading styles.

        .. seealso::

            :ref:`with_polymorphic_mapper_config`

    """
    self.class_ = util.assert_arg_type(class_, type, "class_")
    self._sort_key = "%s.%s" % (
        self.class_.__module__,
        self.class_.__name__,
    )

    self._primary_key_argument = util.to_list(primary_key)
    self.non_primary = non_primary

    self.always_refresh = always_refresh

    if isinstance(version_id_col, MapperProperty):
        self.version_id_prop = version_id_col
        self.version_id_col = None
    else:
        self.version_id_col = (
            coercions.expect(
                roles.ColumnArgumentOrKeyRole,
                version_id_col,
                argname="version_id_col",
            )
            if version_id_col is not None
            else None
        )

    if version_id_generator is False:
        self.version_id_generator = False
    elif version_id_generator is None:
        self.version_id_generator = lambda x: (x or 0) + 1
    else:
        self.version_id_generator = version_id_generator

    self.concrete = concrete
    self.single = False

    if inherits is not None:
        self.inherits = _parse_mapper_argument(inherits)
    else:
        self.inherits = None

    if local_table is not None:
        self.local_table = coercions.expect(
            roles.StrictFromClauseRole,
            local_table,
            disable_inspection=True,
            argname="local_table",
        )
    elif self.inherits:
        # note this is a new flow as of 2.0 so that
        # .local_table need not be Optional
        self.local_table = self.inherits.local_table
        self.single = True
    else:
        raise sa_exc.ArgumentError(
            f"Mapper[{self.class_.__name__}(None)] has None for a "
            "primary table argument and does not specify 'inherits'"
        )

    if inherit_condition is not None:
        self.inherit_condition = coercions.expect(
            roles.OnClauseRole, inherit_condition
        )
    else:
        self.inherit_condition = None

    self.inherit_foreign_keys = inherit_foreign_keys
    self._init_properties = dict(properties) if properties else {}
    self._delete_orphans = []
    self.batch = batch
    self.eager_defaults = eager_defaults
    self.column_prefix = column_prefix

    # interim - polymorphic_on is further refined in
    # _configure_polymorphic_setter
    self.polymorphic_on = (
        coercions.expect(  # type: ignore
            roles.ColumnArgumentOrKeyRole,
            polymorphic_on,
            argname="polymorphic_on",
        )
        if polymorphic_on is not None
        else None
    )
    self.polymorphic_abstract = polymorphic_abstract
    self._dependency_processors = []
    self.validators = util.EMPTY_DICT
    self.passive_updates = passive_updates
    self.passive_deletes = passive_deletes
    self.legacy_is_orphan = legacy_is_orphan
    self._clause_adapter = None
    self._requires_row_aliasing = False
    self._inherits_equated_pairs = None
    self._memoized_values = {}
    self._compiled_cache_size = _compiled_cache_size
    self._reconstructor = None
    self.allow_partial_pks = allow_partial_pks

    if self.inherits and not self.concrete:
        self.confirm_deleted_rows = False
    else:
        self.confirm_deleted_rows = confirm_deleted_rows

    self._set_with_polymorphic(with_polymorphic)
    self.polymorphic_load = polymorphic_load

    # our 'polymorphic identity', a string name that when located in a
    #  result set row indicates this Mapper should be used to construct
    # the object instance for that row.
    self.polymorphic_identity = polymorphic_identity

    # a dictionary of 'polymorphic identity' names, associating those
    # names with Mappers that will be used to construct object instances
    # upon a select operation.
    if _polymorphic_map is None:
        self.polymorphic_map = {}
    else:
        self.polymorphic_map = _polymorphic_map

    if include_properties is not None:
        self.include_properties = util.to_set(include_properties)
    else:
        self.include_properties = None
    if exclude_properties:
        self.exclude_properties = util.to_set(exclude_properties)
    else:
        self.exclude_properties = None

    # prevent this mapper from being constructed
    # while a configure_mappers() is occurring (and defer a
    # configure_mappers() until construction succeeds)
    with _CONFIGURE_MUTEX:
        cast("MapperEvents", self.dispatch._events)._new_mapper_instance(
            class_, self
        )
        self._configure_inheritance()
        self._configure_class_instrumentation()
        self._configure_properties()
        self._configure_polymorphic_setter()
        self._configure_pks()
        self.registry._flag_new_mapper(self)
        self._log("constructed")
        self._expire_memoizations()

    self.dispatch.after_mapper_constructed(self, self.class_)

is_selectable class-attribute instance-attribute

is_selectable = False

Return True if this object is an instance of :class:_expression.Selectable.

is_aliased_class class-attribute instance-attribute

is_aliased_class = False

True if this object is an instance of :class:.AliasedClass.

is_instance class-attribute instance-attribute

is_instance = False

True if this object is an instance of :class:.InstanceState.

is_bundle class-attribute instance-attribute

is_bundle = False

True if this object is an instance of :class:.Bundle.

is_property class-attribute instance-attribute

is_property = False

True if this object is an instance of :class:.MapperProperty.

is_attribute class-attribute instance-attribute

is_attribute = False

True if this object is a Python :term:descriptor.

This can refer to one of many types. Usually a :class:.QueryableAttribute which handles attributes events on behalf of a :class:.MapperProperty. But can also be an extension type such as :class:.AssociationProxy or :class:.hybrid_property. The :attr:.InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

.. seealso::

:attr:`_orm.Mapper.all_orm_descriptors`

is_clause_element class-attribute instance-attribute

is_clause_element = False

True if this object is an instance of :class:_expression.ClauseElement.

extension_type class-attribute instance-attribute

extension_type: InspectionAttrExtensionType = NOT_EXTENSION

The extension type, if any. Defaults to :attr:.interfaces.NotExtension.NOT_EXTENSION

.. seealso::

:class:`.HybridExtensionType`

:class:`.AssociationProxyExtensionType`

inherit_cache class-attribute instance-attribute

inherit_cache: Optional[bool] = None

Indicate if this :class:.HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

.. seealso::

:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.

class_ instance-attribute

class_: Type[_O]

The class to which this :class:_orm.Mapper is mapped.

non_primary instance-attribute

non_primary: bool

Represent True if this :class:_orm.Mapper is a "non-primary" mapper, e.g. a mapper that is used only to select rows but not for persistence management.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

concrete instance-attribute

concrete: bool

Represent True if this :class:_orm.Mapper is a concrete inheritance mapper.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

single instance-attribute

single: bool

Represent True if this :class:_orm.Mapper is a single table inheritance mapper.

:attr:_orm.Mapper.local_table will be None if this flag is set.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

inherits instance-attribute

inherits: Optional[Mapper[Any]]

References the :class:_orm.Mapper which this :class:_orm.Mapper inherits from, if any.

local_table instance-attribute

local_table: FromClause

The immediate :class:_expression.FromClause to which this :class:_orm.Mapper refers.

Typically is an instance of :class:_schema.Table, may be any :class:.FromClause.

The "local" table is the selectable that the :class:_orm.Mapper is directly responsible for managing from an attribute access and flush perspective. For non-inheriting mappers, :attr:.Mapper.local_table will be the same as :attr:.Mapper.persist_selectable. For inheriting mappers, :attr:.Mapper.local_table refers to the specific portion of :attr:.Mapper.persist_selectable that includes the columns to which this :class:.Mapper is loading/persisting, such as a particular :class:.Table within a join.

.. seealso::

:attr:`_orm.Mapper.persist_selectable`.

:attr:`_orm.Mapper.selectable`.

polymorphic_on instance-attribute

polymorphic_on: Optional[KeyedColumnElement[Any]]

The :class:_schema.Column or SQL expression specified as the polymorphic_on argument for this :class:_orm.Mapper, within an inheritance scenario.

This attribute is normally a :class:_schema.Column instance but may also be an expression, such as one derived from :func:.cast.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

validators instance-attribute

validators: immutabledict[str, Tuple[str, Dict[str, Any]]]

An immutable dictionary of attributes which have been decorated using the :func:_orm.validates decorator.

The dictionary contains string attribute names as keys mapped to the actual validation method.

polymorphic_identity instance-attribute

polymorphic_identity: Optional[Any]

Represent an identifier which is matched against the :attr:_orm.Mapper.polymorphic_on column during result row loading.

Used only with inheritance, this object can be of any type which is comparable to the type of column represented by :attr:_orm.Mapper.polymorphic_on.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

polymorphic_map instance-attribute

polymorphic_map: Dict[Any, Mapper[Any]]

A mapping of "polymorphic identity" identifiers mapped to :class:_orm.Mapper instances, within an inheritance scenario.

The identifiers can be of any type which is comparable to the type of column represented by :attr:_orm.Mapper.polymorphic_on.

An inheritance chain of mappers will all reference the same polymorphic map object. The object is used to correlate incoming result rows to target mappers.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

is_mapper class-attribute instance-attribute

is_mapper = True

Part of the inspection API.

mapper property

mapper: Mapper[_O]

Part of the inspection API.

Returns self.

entity property

entity

Part of the inspection API.

Returns self.class_.

tables instance-attribute

A sequence containing the collection of :class:_schema.Table or :class:_schema.TableClause objects which this :class:_orm.Mapper is aware of.

If the mapper is mapped to a :class:_expression.Join, or an :class:_expression.Alias representing a :class:_expression.Select, the individual :class:_schema.Table objects that comprise the full construct will be represented here.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

persist_selectable instance-attribute

persist_selectable: FromClause

The :class:_expression.FromClause to which this :class:_orm.Mapper is mapped.

Typically is an instance of :class:_schema.Table, may be any :class:.FromClause.

The :attr:_orm.Mapper.persist_selectable is similar to :attr:.Mapper.local_table, but represents the :class:.FromClause that represents the inheriting class hierarchy overall in an inheritance scenario.

:attr..Mapper.persist_selectable is also separate from the :attr:.Mapper.selectable attribute, the latter of which may be an alternate subquery used for selecting columns. :attr..Mapper.persist_selectable is oriented towards columns that will be written on a persist operation.

.. seealso::

:attr:`_orm.Mapper.selectable`.

:attr:`_orm.Mapper.local_table`.

configured class-attribute instance-attribute

configured: bool = False

Represent True if this :class:_orm.Mapper has been configured.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

.. seealso::

:func:`.configure_mappers`.

primary_key instance-attribute

primary_key: Tuple[Column[Any], ...]

An iterable containing the collection of :class:_schema.Column objects which comprise the 'primary key' of the mapped table, from the perspective of this :class:_orm.Mapper.

This list is against the selectable in :attr:_orm.Mapper.persist_selectable. In the case of inheriting mappers, some columns may be managed by a superclass mapper. For example, in the case of a :class:_expression.Join, the primary key is determined by all of the primary key columns across all tables referenced by the :class:_expression.Join.

The list is also not necessarily the same as the primary key column collection associated with the underlying tables; the :class:_orm.Mapper features a primary_key argument that can override what the :class:_orm.Mapper considers as primary key columns.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

class_manager instance-attribute

class_manager: ClassManager[_O]

The :class:.ClassManager which maintains event listeners and class-bound descriptors for this :class:_orm.Mapper.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

base_mapper instance-attribute

base_mapper: Mapper[Any]

The base-most :class:_orm.Mapper in an inheritance chain.

In a non-inheriting scenario, this attribute will always be this :class:_orm.Mapper. In an inheritance scenario, it references the :class:_orm.Mapper which is parent to all other :class:_orm.Mapper objects in the inheritance chain.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

columns instance-attribute

columns: ReadOnlyColumnCollection[str, Column[Any]]

A collection of :class:_schema.Column or other scalar expression objects maintained by this :class:_orm.Mapper.

The collection behaves the same as that of the c attribute on any :class:_schema.Table object, except that only those columns included in this mapping are present, and are keyed based on the attribute name defined in the mapping, not necessarily the key attribute of the :class:_schema.Column itself. Additionally, scalar expressions mapped by :func:.column_property are also present here.

This is a read only attribute determined during mapper construction. Behavior is undefined if directly modified.

c instance-attribute

c: ReadOnlyColumnCollection[str, Column[Any]]

A synonym for :attr:_orm.Mapper.columns.

iterate_properties property

iterate_properties

return an iterator of all MapperProperty objects.

with_polymorphic_mappers class-attribute instance-attribute

with_polymorphic_mappers = _with_polymorphic_mappers

The list of :class:_orm.Mapper objects included in the default "polymorphic" query.

selectable property

selectable: FromClause

The :class:_schema.FromClause construct this :class:_orm.Mapper selects from by default.

Normally, this is equivalent to :attr:.persist_selectable, unless the with_polymorphic feature is in use, in which case the full "polymorphic" selectable is returned.

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

Bases: memoized_property[_T]

A read-only @property that is only evaluated once.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

add_properties

add_properties(dict_of_properties)

Add the given dictionary of properties to this mapper, using add_property.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def add_properties(self, dict_of_properties):
    """Add the given dictionary of properties to this mapper,
    using `add_property`.

    """
    for key, value in dict_of_properties.items():
        self.add_property(key, value)

add_property

add_property(
    key: str, prop: Union[Column[Any], MapperProperty[Any]]
) -> None

Add an individual MapperProperty to this mapper.

If the mapper has not been configured yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been configured, then the given MapperProperty is configured immediately.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def add_property(
    self, key: str, prop: Union[Column[Any], MapperProperty[Any]]
) -> None:
    """Add an individual MapperProperty to this mapper.

    If the mapper has not been configured yet, just adds the
    property to the initial properties dictionary sent to the
    constructor.  If this Mapper has already been configured, then
    the given MapperProperty is configured immediately.

    """
    prop = self._configure_property(
        key, prop, init=self.configured, warn_for_existing=True
    )
    assert isinstance(prop, MapperProperty)
    self._init_properties[key] = prop

get_property

get_property(
    key: str, _configure_mappers: bool = False
) -> MapperProperty[Any]

return a MapperProperty associated with the given key.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def get_property(
    self, key: str, _configure_mappers: bool = False
) -> MapperProperty[Any]:
    """return a MapperProperty associated with the given key."""

    if _configure_mappers:
        self._check_configure()

    try:
        return self._props[key]
    except KeyError as err:
        raise sa_exc.InvalidRequestError(
            f"Mapper '{self}' has no property '{key}'.  If this property "
            "was indicated from other mappers or configure events, ensure "
            "registry.configure() has been called."
        ) from err

get_property_by_column

get_property_by_column(
    column: ColumnElement[_T],
) -> MapperProperty[_T]

Given a :class:_schema.Column object, return the :class:.MapperProperty which maps this column.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def get_property_by_column(
    self, column: ColumnElement[_T]
) -> MapperProperty[_T]:
    """Given a :class:`_schema.Column` object, return the
    :class:`.MapperProperty` which maps this column."""

    return self._columntoproperty[column]

attrs

attrs() -> ReadOnlyProperties[MapperProperty[Any]]

A namespace of all :class:.MapperProperty objects associated this mapper.

This is an object that provides each property based on its key name. For instance, the mapper for a User class which has User.name attribute would provide mapper.attrs.name, which would be the :class:.ColumnProperty representing the name column. The namespace object can also be iterated, which would yield each :class:.MapperProperty.

:class:_orm.Mapper has several pre-filtered views of this attribute which limit the types of properties returned, including :attr:.synonyms, :attr:.column_attrs, :attr:.relationships, and :attr:.composites.

.. warning::

The :attr:`_orm.Mapper.attrs` accessor namespace is an
instance of :class:`.OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.attrs[somename]`` over
``getattr(mapper.attrs, somename)`` to avoid name collisions.

.. seealso::

:attr:`_orm.Mapper.all_orm_descriptors`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
def attrs(self) -> util.ReadOnlyProperties[MapperProperty[Any]]:
    """A namespace of all :class:`.MapperProperty` objects
    associated this mapper.

    This is an object that provides each property based on
    its key name.  For instance, the mapper for a
    ``User`` class which has ``User.name`` attribute would
    provide ``mapper.attrs.name``, which would be the
    :class:`.ColumnProperty` representing the ``name``
    column.   The namespace object can also be iterated,
    which would yield each :class:`.MapperProperty`.

    :class:`_orm.Mapper` has several pre-filtered views
    of this attribute which limit the types of properties
    returned, including :attr:`.synonyms`, :attr:`.column_attrs`,
    :attr:`.relationships`, and :attr:`.composites`.

    .. warning::

        The :attr:`_orm.Mapper.attrs` accessor namespace is an
        instance of :class:`.OrderedProperties`.  This is
        a dictionary-like object which includes a small number of
        named methods such as :meth:`.OrderedProperties.items`
        and :meth:`.OrderedProperties.values`.  When
        accessing attributes dynamically, favor using the dict-access
        scheme, e.g. ``mapper.attrs[somename]`` over
        ``getattr(mapper.attrs, somename)`` to avoid name collisions.

    .. seealso::

        :attr:`_orm.Mapper.all_orm_descriptors`

    """

    self._check_configure()
    return util.ReadOnlyProperties(self._props)

all_orm_descriptors

all_orm_descriptors() -> ReadOnlyProperties[InspectionAttr]

A namespace of all :class:.InspectionAttr attributes associated with the mapped class.

These attributes are in all cases Python :term:descriptors associated with the mapped class or its superclasses.

This namespace includes attributes that are mapped to the class as well as attributes declared by extension modules. It includes any Python descriptor type that inherits from :class:.InspectionAttr. This includes :class:.QueryableAttribute, as well as extension types such as :class:.hybrid_property, :class:.hybrid_method and :class:.AssociationProxy.

To distinguish between mapped attributes and extension attributes, the attribute :attr:.InspectionAttr.extension_type will refer to a constant that distinguishes between different extension types.

The sorting of the attributes is based on the following rules:

  1. Iterate through the class and its superclasses in order from subclass to superclass (i.e. iterate through cls.__mro__)

  2. For each class, yield the attributes in the order in which they appear in __dict__, with the exception of those in step 3 below. In Python 3.6 and above this ordering will be the same as that of the class' construction, with the exception of attributes that were added after the fact by the application or the mapper.

  3. If a certain attribute key is also in the superclass __dict__, then it's included in the iteration for that class, and not the class in which it first appeared.

The above process produces an ordering that is deterministic in terms of the order in which attributes were assigned to the class.

.. versionchanged:: 1.3.19 ensured deterministic ordering for :meth:_orm.Mapper.all_orm_descriptors.

When dealing with a :class:.QueryableAttribute, the :attr:.QueryableAttribute.property attribute refers to the :class:.MapperProperty property, which is what you get when referring to the collection of mapped properties via :attr:_orm.Mapper.attrs.

.. warning::

The :attr:`_orm.Mapper.all_orm_descriptors`
accessor namespace is an
instance of :class:`.OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.all_orm_descriptors[somename]`` over
``getattr(mapper.all_orm_descriptors, somename)`` to avoid name
collisions.

.. seealso::

:attr:`_orm.Mapper.attrs`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
def all_orm_descriptors(self) -> util.ReadOnlyProperties[InspectionAttr]:
    """A namespace of all :class:`.InspectionAttr` attributes associated
    with the mapped class.

    These attributes are in all cases Python :term:`descriptors`
    associated with the mapped class or its superclasses.

    This namespace includes attributes that are mapped to the class
    as well as attributes declared by extension modules.
    It includes any Python descriptor type that inherits from
    :class:`.InspectionAttr`.  This includes
    :class:`.QueryableAttribute`, as well as extension types such as
    :class:`.hybrid_property`, :class:`.hybrid_method` and
    :class:`.AssociationProxy`.

    To distinguish between mapped attributes and extension attributes,
    the attribute :attr:`.InspectionAttr.extension_type` will refer
    to a constant that distinguishes between different extension types.

    The sorting of the attributes is based on the following rules:

    1. Iterate through the class and its superclasses in order from
       subclass to superclass (i.e. iterate through ``cls.__mro__``)

    2. For each class, yield the attributes in the order in which they
       appear in ``__dict__``, with the exception of those in step
       3 below.  In Python 3.6 and above this ordering will be the
       same as that of the class' construction, with the exception
       of attributes that were added after the fact by the application
       or the mapper.

    3. If a certain attribute key is also in the superclass ``__dict__``,
       then it's included in the iteration for that class, and not the
       class in which it first appeared.

    The above process produces an ordering that is deterministic in terms
    of the order in which attributes were assigned to the class.

    .. versionchanged:: 1.3.19 ensured deterministic ordering for
       :meth:`_orm.Mapper.all_orm_descriptors`.

    When dealing with a :class:`.QueryableAttribute`, the
    :attr:`.QueryableAttribute.property` attribute refers to the
    :class:`.MapperProperty` property, which is what you get when
    referring to the collection of mapped properties via
    :attr:`_orm.Mapper.attrs`.

    .. warning::

        The :attr:`_orm.Mapper.all_orm_descriptors`
        accessor namespace is an
        instance of :class:`.OrderedProperties`.  This is
        a dictionary-like object which includes a small number of
        named methods such as :meth:`.OrderedProperties.items`
        and :meth:`.OrderedProperties.values`.  When
        accessing attributes dynamically, favor using the dict-access
        scheme, e.g. ``mapper.all_orm_descriptors[somename]`` over
        ``getattr(mapper.all_orm_descriptors, somename)`` to avoid name
        collisions.

    .. seealso::

        :attr:`_orm.Mapper.attrs`

    """
    return util.ReadOnlyProperties(
        dict(self.class_manager._all_sqla_attributes())
    )

synonyms

synonyms() -> ReadOnlyProperties[SynonymProperty[Any]]

Return a namespace of all :class:.Synonym properties maintained by this :class:_orm.Mapper.

.. seealso::

:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
@util.preload_module("sqlalchemy.orm.descriptor_props")
def synonyms(self) -> util.ReadOnlyProperties[SynonymProperty[Any]]:
    """Return a namespace of all :class:`.Synonym`
    properties maintained by this :class:`_orm.Mapper`.

    .. seealso::

        :attr:`_orm.Mapper.attrs` - namespace of all
        :class:`.MapperProperty`
        objects.

    """
    descriptor_props = util.preloaded.orm_descriptor_props

    return self._filter_properties(descriptor_props.SynonymProperty)

column_attrs

column_attrs() -> ReadOnlyProperties[ColumnProperty[Any]]

Return a namespace of all :class:.ColumnProperty properties maintained by this :class:_orm.Mapper.

.. seealso::

:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
def column_attrs(self) -> util.ReadOnlyProperties[ColumnProperty[Any]]:
    """Return a namespace of all :class:`.ColumnProperty`
    properties maintained by this :class:`_orm.Mapper`.

    .. seealso::

        :attr:`_orm.Mapper.attrs` - namespace of all
        :class:`.MapperProperty`
        objects.

    """
    return self._filter_properties(properties.ColumnProperty)

relationships

relationships() -> ReadOnlyProperties[
    RelationshipProperty[Any]
]

A namespace of all :class:.Relationship properties maintained by this :class:_orm.Mapper.

.. warning::

the :attr:`_orm.Mapper.relationships` accessor namespace is an
instance of :class:`.OrderedProperties`.  This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`.  When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.relationships[somename]`` over
``getattr(mapper.relationships, somename)`` to avoid name
collisions.

.. seealso::

:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
@util.preload_module("sqlalchemy.orm.relationships")
def relationships(
    self,
) -> util.ReadOnlyProperties[RelationshipProperty[Any]]:
    """A namespace of all :class:`.Relationship` properties
    maintained by this :class:`_orm.Mapper`.

    .. warning::

        the :attr:`_orm.Mapper.relationships` accessor namespace is an
        instance of :class:`.OrderedProperties`.  This is
        a dictionary-like object which includes a small number of
        named methods such as :meth:`.OrderedProperties.items`
        and :meth:`.OrderedProperties.values`.  When
        accessing attributes dynamically, favor using the dict-access
        scheme, e.g. ``mapper.relationships[somename]`` over
        ``getattr(mapper.relationships, somename)`` to avoid name
        collisions.

    .. seealso::

        :attr:`_orm.Mapper.attrs` - namespace of all
        :class:`.MapperProperty`
        objects.

    """
    return self._filter_properties(
        util.preloaded.orm_relationships.RelationshipProperty
    )

composites

composites() -> ReadOnlyProperties[CompositeProperty[Any]]

Return a namespace of all :class:.Composite properties maintained by this :class:_orm.Mapper.

.. seealso::

:attr:`_orm.Mapper.attrs` - namespace of all
:class:`.MapperProperty`
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
@util.preload_module("sqlalchemy.orm.descriptor_props")
def composites(self) -> util.ReadOnlyProperties[CompositeProperty[Any]]:
    """Return a namespace of all :class:`.Composite`
    properties maintained by this :class:`_orm.Mapper`.

    .. seealso::

        :attr:`_orm.Mapper.attrs` - namespace of all
        :class:`.MapperProperty`
        objects.

    """
    return self._filter_properties(
        util.preloaded.orm_descriptor_props.CompositeProperty
    )

common_parent

common_parent(other: Mapper[Any]) -> bool

Return true if the given mapper shares a common inherited parent as this mapper.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def common_parent(self, other: Mapper[Any]) -> bool:
    """Return true if the given mapper shares a
    common inherited parent as this mapper."""

    return self.base_mapper is other.base_mapper

is_sibling

is_sibling(other: Mapper[Any]) -> bool

return true if the other mapper is an inheriting sibling to this one. common parent but different branch

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def is_sibling(self, other: Mapper[Any]) -> bool:
    """return true if the other mapper is an inheriting sibling to this
    one.  common parent but different branch

    """
    return (
        self.base_mapper is other.base_mapper
        and not self.isa(other)
        and not other.isa(self)
    )

isa

isa(other: Mapper[Any]) -> bool

Return True if the this mapper inherits from the given mapper.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def isa(self, other: Mapper[Any]) -> bool:
    """Return True if the this mapper inherits from the given mapper."""

    m: Optional[Mapper[Any]] = self
    while m and m is not other:
        m = m.inherits
    return bool(m)

self_and_descendants

self_and_descendants() -> Sequence[Mapper[Any]]

The collection including this mapper and all descendant mappers.

This includes not just the immediately inheriting mappers but all their inheriting mappers as well.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
@HasMemoized.memoized_attribute
def self_and_descendants(self) -> Sequence[Mapper[Any]]:
    """The collection including this mapper and all descendant mappers.

    This includes not just the immediately inheriting mappers but
    all their inheriting mappers as well.

    """
    descendants = []
    stack = deque([self])
    while stack:
        item = stack.popleft()
        descendants.append(item)
        stack.extend(item._inheriting_mappers)
    return util.WeakSequence(descendants)

polymorphic_iterator

polymorphic_iterator() -> Iterator[Mapper[Any]]

Iterate through the collection including this mapper and all descendant mappers.

This includes not just the immediately inheriting mappers but all their inheriting mappers as well.

To iterate through an entire hierarchy, use mapper.base_mapper.polymorphic_iterator().

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def polymorphic_iterator(self) -> Iterator[Mapper[Any]]:
    """Iterate through the collection including this mapper and
    all descendant mappers.

    This includes not just the immediately inheriting mappers but
    all their inheriting mappers as well.

    To iterate through an entire hierarchy, use
    ``mapper.base_mapper.polymorphic_iterator()``.

    """
    return iter(self.self_and_descendants)

primary_mapper

primary_mapper() -> Mapper[Any]

Return the primary mapper corresponding to this mapper's class key (class).

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def primary_mapper(self) -> Mapper[Any]:
    """Return the primary mapper corresponding to this mapper's class key
    (class)."""

    return self.class_manager.mapper

identity_key_from_row

identity_key_from_row(
    row: Optional[Union[Row[Any], RowMapping]],
    identity_token: Optional[Any] = None,
    adapter: Optional[ORMAdapter] = None,
) -> _IdentityKeyType[_O]

Return an identity-map key for use in storing/retrieving an item from the identity map.

:param row: A :class:.Row or :class:.RowMapping produced from a result set that selected from the ORM mapped primary key columns.

.. versionchanged:: 2.0 :class:.Row or :class:.RowMapping are accepted for the "row" argument

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def identity_key_from_row(
    self,
    row: Optional[Union[Row[Any], RowMapping]],
    identity_token: Optional[Any] = None,
    adapter: Optional[ORMAdapter] = None,
) -> _IdentityKeyType[_O]:
    """Return an identity-map key for use in storing/retrieving an
    item from the identity map.

    :param row: A :class:`.Row` or :class:`.RowMapping` produced from a
     result set that selected from the ORM mapped primary key columns.

     .. versionchanged:: 2.0
        :class:`.Row` or :class:`.RowMapping` are accepted
        for the "row" argument

    """
    pk_cols: Sequence[ColumnClause[Any]] = self.primary_key
    if adapter:
        pk_cols = [adapter.columns[c] for c in pk_cols]

    if hasattr(row, "_mapping"):
        mapping = row._mapping  # type: ignore
    else:
        mapping = cast("Mapping[Any, Any]", row)

    return (
        self._identity_class,
        tuple(mapping[column] for column in pk_cols),  # type: ignore
        identity_token,
    )

identity_key_from_primary_key

identity_key_from_primary_key(
    primary_key: Tuple[Any, ...],
    identity_token: Optional[Any] = None,
) -> _IdentityKeyType[_O]

Return an identity-map key for use in storing/retrieving an item from an identity map.

:param primary_key: A list of values indicating the identifier.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def identity_key_from_primary_key(
    self,
    primary_key: Tuple[Any, ...],
    identity_token: Optional[Any] = None,
) -> _IdentityKeyType[_O]:
    """Return an identity-map key for use in storing/retrieving an
    item from an identity map.

    :param primary_key: A list of values indicating the identifier.

    """
    return (
        self._identity_class,
        tuple(primary_key),
        identity_token,
    )

identity_key_from_instance

identity_key_from_instance(
    instance: _O,
) -> _IdentityKeyType[_O]

Return the identity key for the given instance, based on its primary key attributes.

If the instance's state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:~sqlalchemy.orm.exc.ObjectDeletedError is raised.

This value is typically also found on the instance state under the attribute name key.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def identity_key_from_instance(self, instance: _O) -> _IdentityKeyType[_O]:
    """Return the identity key for the given instance, based on
    its primary key attributes.

    If the instance's state is expired, calling this method
    will result in a database check to see if the object has been deleted.
    If the row no longer exists,
    :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.

    This value is typically also found on the instance state under the
    attribute name `key`.

    """
    state = attributes.instance_state(instance)
    return self._identity_key_from_state(state, PassiveFlag.PASSIVE_OFF)

primary_key_from_instance

primary_key_from_instance(instance: _O) -> Tuple[Any, ...]

Return the list of primary key values for the given instance.

If the instance's state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:~sqlalchemy.orm.exc.ObjectDeletedError is raised.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def primary_key_from_instance(self, instance: _O) -> Tuple[Any, ...]:
    """Return the list of primary key values for the given
    instance.

    If the instance's state is expired, calling this method
    will result in a database check to see if the object has been deleted.
    If the row no longer exists,
    :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.

    """
    state = attributes.instance_state(instance)
    identity_key = self._identity_key_from_state(
        state, PassiveFlag.PASSIVE_OFF
    )
    return identity_key[1]

cascade_iterator

cascade_iterator(
    type_: str,
    state: InstanceState[_O],
    halt_on: Optional[
        Callable[[InstanceState[Any]], bool]
    ] = None,
) -> Iterator[
    Tuple[
        object,
        Mapper[Any],
        InstanceState[Any],
        _InstanceDict,
    ]
]

Iterate each element and its mapper in an object graph, for all relationships that meet the given cascade rule.

:param type_: The name of the cascade rule (i.e. "save-update", "delete", etc.).

.. note:: the "all" cascade is not accepted here. For a generic object traversal function, see :ref:faq_walk_objects.

:param state: The lead InstanceState. child items will be processed per the relationships defined for this object's mapper.

:return: the method yields individual object instances.

.. seealso::

:ref:`unitofwork_cascades`

:ref:`faq_walk_objects` - illustrates a generic function to
traverse all objects without relying on cascades.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/mapper.py
def cascade_iterator(
    self,
    type_: str,
    state: InstanceState[_O],
    halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
) -> Iterator[
    Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
]:
    r"""Iterate each element and its mapper in an object graph,
    for all relationships that meet the given cascade rule.

    :param type\_:
      The name of the cascade rule (i.e. ``"save-update"``, ``"delete"``,
      etc.).

      .. note::  the ``"all"`` cascade is not accepted here.  For a generic
         object traversal function, see :ref:`faq_walk_objects`.

    :param state:
      The lead InstanceState.  child items will be processed per
      the relationships defined for this object's mapper.

    :return: the method yields individual object instances.

    .. seealso::

        :ref:`unitofwork_cascades`

        :ref:`faq_walk_objects` - illustrates a generic function to
        traverse all objects without relying on cascades.

    """
    visited_states: Set[InstanceState[Any]] = set()
    prp, mpp = object(), object()

    assert state.mapper.isa(self)

    # this is actually a recursive structure, fully typing it seems
    # a little too difficult for what it's worth here
    visitables: Deque[
        Tuple[
            Deque[Any],
            object,
            Optional[InstanceState[Any]],
            Optional[_InstanceDict],
        ]
    ]

    visitables = deque(
        [(deque(state.mapper._props.values()), prp, state, state.dict)]
    )

    while visitables:
        iterator, item_type, parent_state, parent_dict = visitables[-1]
        if not iterator:
            visitables.pop()
            continue

        if item_type is prp:
            prop = iterator.popleft()
            if not prop.cascade or type_ not in prop.cascade:
                continue
            assert parent_state is not None
            assert parent_dict is not None
            queue = deque(
                prop.cascade_iterator(
                    type_,
                    parent_state,
                    parent_dict,
                    visited_states,
                    halt_on,
                )
            )
            if queue:
                visitables.append((queue, mpp, None, None))
        elif item_type is mpp:
            (
                instance,
                instance_mapper,
                corresponding_state,
                corresponding_dict,
            ) = iterator.popleft()
            yield (
                instance,
                instance_mapper,
                corresponding_state,
                corresponding_dict,
            )
            visitables.append(
                (
                    deque(instance_mapper._props.values()),
                    prp,
                    corresponding_state,
                    corresponding_dict,
                )
            )

Mutable

Bases: MutableBase

Mixin that defines transparent propagation of change events to a parent object.

See the example in :ref:mutable_scalars for usage information.

coerce classmethod

coerce(key: str, value: Any) -> Optional[Any]

Given a value, coerce it into the target type.

Can be overridden by custom subclasses to coerce incoming data into a particular type.

By default, raises ValueError.

This method is called in different scenarios depending on if the parent class is of type :class:.Mutable or of type :class:.MutableComposite. In the case of the former, it is called for both attribute-set operations as well as during ORM loading operations. For the latter, it is only called during attribute-set operations; the mechanics of the :func:.composite construct handle coercion during load operations.

:param key: string name of the ORM-mapped attribute being set. :param value: the incoming value. :return: the method should return the coerced value, or raise ValueError if the coercion cannot be completed.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
@classmethod
def coerce(cls, key: str, value: Any) -> Optional[Any]:
    """Given a value, coerce it into the target type.

    Can be overridden by custom subclasses to coerce incoming
    data into a particular type.

    By default, raises ``ValueError``.

    This method is called in different scenarios depending on if
    the parent class is of type :class:`.Mutable` or of type
    :class:`.MutableComposite`.  In the case of the former, it is called
    for both attribute-set operations as well as during ORM loading
    operations.  For the latter, it is only called during attribute-set
    operations; the mechanics of the :func:`.composite` construct
    handle coercion during load operations.


    :param key: string name of the ORM-mapped attribute being set.
    :param value: the incoming value.
    :return: the method should return the coerced value, or raise
     ``ValueError`` if the coercion cannot be completed.

    """
    if value is None:
        return None
    msg = "Attribute '%s' does not accept objects of type %s"
    raise ValueError(msg % (key, type(value)))

changed

changed() -> None

Subclasses should call this method whenever change events occur.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
def changed(self) -> None:
    """Subclasses should call this method whenever change events occur."""

    for parent, key in self._parents.items():
        flag_modified(parent.obj(), key)

associate_with_attribute classmethod

associate_with_attribute(
    attribute: InstrumentedAttribute[_O],
) -> None

Establish this type as a mutation listener for the given mapped descriptor.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
@classmethod
def associate_with_attribute(
    cls, attribute: InstrumentedAttribute[_O]
) -> None:
    """Establish this type as a mutation listener for the given
    mapped descriptor.

    """
    cls._listen_on_attribute(attribute, True, attribute.class_)

associate_with classmethod

associate_with(sqltype: type) -> None

Associate this wrapper with all future mapped columns of the given type.

This is a convenience method that calls associate_with_attribute automatically.

.. warning::

The listeners established by this method are global to all mappers, and are not garbage collected. Only use :meth:.associate_with for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
@classmethod
def associate_with(cls, sqltype: type) -> None:
    """Associate this wrapper with all future mapped columns
    of the given type.

    This is a convenience method that calls
    ``associate_with_attribute`` automatically.

    .. warning::

       The listeners established by this method are *global*
       to all mappers, and are *not* garbage collected.   Only use
       :meth:`.associate_with` for types that are permanent to an
       application, not with ad-hoc types else this will cause unbounded
       growth in memory usage.

    """

    def listen_for_type(mapper: Mapper[_O], class_: type) -> None:
        if mapper.non_primary:
            return
        for prop in mapper.column_attrs:
            if isinstance(prop.columns[0].type, sqltype):
                cls.associate_with_attribute(getattr(class_, prop.key))

    event.listen(Mapper, "mapper_configured", listen_for_type)

as_mutable classmethod

as_mutable(sqltype: TypeEngine[_T]) -> TypeEngine[_T]

Associate a SQL type with this mutable Python type.

This establishes listeners that will detect ORM mappings against the given type, adding mutation event trackers to those mappings.

The type is returned, unconditionally as an instance, so that :meth:.as_mutable can be used inline::

Table('mytable', metadata,
    Column('id', Integer, primary_key=True),
    Column('data', MyMutableType.as_mutable(PickleType))
)

Note that the returned type is always an instance, even if a class is given, and that only columns which are declared specifically with that type instance receive additional instrumentation.

To associate a particular mutable type with all occurrences of a particular type, use the :meth:.Mutable.associate_with classmethod of the particular :class:.Mutable subclass to establish a global association.

.. warning::

The listeners established by this method are global to all mappers, and are not garbage collected. Only use :meth:.as_mutable for types that are permanent to an application, not with ad-hoc types else this will cause unbounded growth in memory usage.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/mutable.py
@classmethod
def as_mutable(cls, sqltype: TypeEngine[_T]) -> TypeEngine[_T]:
    """Associate a SQL type with this mutable Python type.

    This establishes listeners that will detect ORM mappings against
    the given type, adding mutation event trackers to those mappings.

    The type is returned, unconditionally as an instance, so that
    :meth:`.as_mutable` can be used inline::

        Table('mytable', metadata,
            Column('id', Integer, primary_key=True),
            Column('data', MyMutableType.as_mutable(PickleType))
        )

    Note that the returned type is always an instance, even if a class
    is given, and that only columns which are declared specifically with
    that type instance receive additional instrumentation.

    To associate a particular mutable type with all occurrences of a
    particular type, use the :meth:`.Mutable.associate_with` classmethod
    of the particular :class:`.Mutable` subclass to establish a global
    association.

    .. warning::

       The listeners established by this method are *global*
       to all mappers, and are *not* garbage collected.   Only use
       :meth:`.as_mutable` for types that are permanent to an application,
       not with ad-hoc types else this will cause unbounded growth
       in memory usage.

    """
    sqltype = types.to_instance(sqltype)

    # a SchemaType will be copied when the Column is copied,
    # and we'll lose our ability to link that type back to the original.
    # so track our original type w/ columns
    if isinstance(sqltype, SchemaEventTarget):

        @event.listens_for(sqltype, "before_parent_attach")
        def _add_column_memo(
            sqltyp: TypeEngine[Any],
            parent: Column[_T],
        ) -> None:
            parent.info["_ext_mutable_orig_type"] = sqltyp

        schema_event_check = True
    else:
        schema_event_check = False

    def listen_for_type(
        mapper: Mapper[_T],
        class_: Union[DeclarativeAttributeIntercept, type],
    ) -> None:
        if mapper.non_primary:
            return
        _APPLIED_KEY = "_ext_mutable_listener_applied"

        for prop in mapper.column_attrs:
            if (
                # all Mutable types refer to a Column that's mapped,
                # since this is the only kind of Core target the ORM can
                # "mutate"
                isinstance(prop.expression, Column)
                and (
                    (
                        schema_event_check
                        and prop.expression.info.get(
                            "_ext_mutable_orig_type"
                        )
                        is sqltype
                    )
                    or prop.expression.type is sqltype
                )
            ):
                if not prop.expression.info.get(_APPLIED_KEY, False):
                    prop.expression.info[_APPLIED_KEY] = True
                    cls.associate_with_attribute(getattr(class_, prop.key))

    event.listen(Mapper, "mapper_configured", listen_for_type)

    return sqltype

ORMOption

Bases: ExecutableOption

Base class for option objects that are passed to ORM queries.

These options may be consumed by :meth:.Query.options, :meth:.Select.options, or in a more general sense by any :meth:.Executable.options method. They are interpreted at statement compile time or execution time in modern use. The deprecated :class:.MapperOption is consumed at ORM query construction time.

.. versionadded:: 1.4

propagate_to_loaders class-attribute instance-attribute

propagate_to_loaders = False

if True, indicate this option should be carried along to "secondary" SELECT statements that occur for relationship lazy loaders as well as attribute load / refresh operations.

get_children

get_children(
    *, omit_attrs: Tuple[str, ...] = (), **kw: Any
) -> Iterable[HasTraverseInternals]

Return immediate child :class:.visitors.HasTraverseInternals elements of this :class:.visitors.HasTraverseInternals.

This is used for visit traversal.

**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/visitors.py
@util.preload_module("sqlalchemy.sql.traversals")
def get_children(
    self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any
) -> Iterable[HasTraverseInternals]:
    r"""Return immediate child :class:`.visitors.HasTraverseInternals`
    elements of this :class:`.visitors.HasTraverseInternals`.

    This is used for visit traversal.

    \**kw may contain flags that change the collection that is
    returned, for example to return a subset of items in order to
    cut down on larger traversals, or to return child items from a
    different context (such as schema-level collections instead of
    clause-level).

    """

    traversals = util.preloaded.sql_traversals

    try:
        traverse_internals = self._traverse_internals
    except AttributeError:
        # user-defined classes may not have a _traverse_internals
        return []

    dispatch = traversals._get_children.run_generated_dispatch
    return itertools.chain.from_iterable(
        meth(obj, **kw)
        for attrname, obj, meth in dispatch(
            self, traverse_internals, "_generated_get_children_traversal"
        )
        if attrname not in omit_attrs and obj is not None
    )

Query

Query(
    entities: Union[
        _ColumnsClauseArgument[Any],
        Sequence[_ColumnsClauseArgument[Any]],
    ],
    session: Optional[Session] = None,
)

Bases: _SelectFromElements, SupportsCloneAnnotations, HasPrefixes, HasSuffixes, HasHints, EventTarget, Identified, Generative, Executable, Generic[_T]

ORM-level SQL construction object.

.. legacy:: The ORM :class:.Query object is a legacy construct as of SQLAlchemy 2.0. See the notes at the top of :ref:query_api_toplevel for an overview, including links to migration documentation.

:class:_query.Query objects are normally initially generated using the :meth:~.Session.query method of :class:.Session, and in less common cases by instantiating the :class:_query.Query directly and associating with a :class:.Session using the :meth:_query.Query.with_session method.

Construct a :class:_query.Query directly.

E.g.::

q = Query([User, Address], session=some_session)

The above is equivalent to::

q = some_session.query(User, Address)

:param entities: a sequence of entities and/or SQL expressions.

:param session: a :class:.Session with which the :class:_query.Query will be associated. Optional; a :class:_query.Query can be associated with a :class:.Session generatively via the :meth:_query.Query.with_session method as well.

.. seealso::

:meth:`.Session.query`

:meth:`_query.Query.with_session`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def __init__(
    self,
    entities: Union[
        _ColumnsClauseArgument[Any], Sequence[_ColumnsClauseArgument[Any]]
    ],
    session: Optional[Session] = None,
):
    """Construct a :class:`_query.Query` directly.

    E.g.::

        q = Query([User, Address], session=some_session)

    The above is equivalent to::

        q = some_session.query(User, Address)

    :param entities: a sequence of entities and/or SQL expressions.

    :param session: a :class:`.Session` with which the
     :class:`_query.Query`
     will be associated.   Optional; a :class:`_query.Query`
     can be associated
     with a :class:`.Session` generatively via the
     :meth:`_query.Query.with_session` method as well.

    .. seealso::

        :meth:`.Session.query`

        :meth:`_query.Query.with_session`

    """

    # session is usually present.  There's one case in subqueryloader
    # where it stores a Query without a Session and also there are tests
    # for the query(Entity).with_session(session) API which is likely in
    # some old recipes, however these are legacy as select() can now be
    # used.
    self.session = session  # type: ignore
    self._set_entities(entities)

statement property

statement: Union[Select[_T], FromStatement[_T]]

The full SELECT statement represented by this Query.

The statement by default will not have disambiguating labels applied to the construct unless with_labels(True) is called first.

selectable property

selectable: Union[Select[_T], FromStatement[_T]]

Return the :class:_expression.Select object emitted by this :class:_query.Query.

Used for :func:_sa.inspect compatibility, this is equivalent to::

query.enable_eagerloads(False).with_labels().statement

is_single_entity property

is_single_entity: bool

Indicates if this :class:_query.Query returns tuples or single entities.

Returns True if this query returns a single entity for each instance in its result list, and False if this query returns a tuple of entities for each result.

.. versionadded:: 1.3.11

.. seealso::

:meth:`_query.Query.only_return_tuples`

get_label_style property

get_label_style: SelectLabelStyle

Retrieve the current label style.

.. versionadded:: 1.4

.. seealso::

:meth:`_sql.Select.get_label_style` - v2 equivalent method.

whereclause property

whereclause: Optional[ColumnElement[bool]]

A readonly attribute which returns the current WHERE criterion for this Query.

This returned value is a SQL expression construct, or None if no criterion has been established.

.. seealso::

:attr:`_sql.Select.whereclause` - v2 equivalent property.

lazy_loaded_from property

lazy_loaded_from: Optional[InstanceState[Any]]

An :class:.InstanceState that is using this :class:_query.Query for a lazy load operation.

.. deprecated:: 1.4 This attribute should be viewed via the :attr:.ORMExecuteState.lazy_loaded_from attribute, within the context of the :meth:.SessionEvents.do_orm_execute event.

.. seealso::

:attr:`.ORMExecuteState.lazy_loaded_from`

column_descriptions property

column_descriptions: List[ORMColumnDescription]

Return metadata about the columns which would be returned by this :class:_query.Query.

Format is a list of dictionaries::

user_alias = aliased(User, name='user2')
q = sess.query(User, User.id, user_alias)

# this expression:
q.column_descriptions

# would return:
[
    {
        'name':'User',
        'type':User,
        'aliased':False,
        'expr':User,
        'entity': User
    },
    {
        'name':'id',
        'type':Integer(),
        'aliased':False,
        'expr':User.id,
        'entity': User
    },
    {
        'name':'user2',
        'type':User,
        'aliased':True,
        'expr':user_alias,
        'entity': user_alias
    }
]

.. seealso::

This API is available using :term:`2.0 style` queries as well,
documented at:

* :ref:`queryguide_inspection`

* :attr:`.Select.column_descriptions`

memoized_attribute

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

Bases: memoized_property[_T]

A read-only @property that is only evaluated once.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

with_statement_hint

with_statement_hint(
    text: str, dialect_name: str = "*"
) -> Self

Add a statement hint to this :class:_expression.Select or other selectable object.

This method is similar to :meth:_expression.Select.with_hint except that it does not require an individual table, and instead applies to the statement as a whole.

Hints here are specific to the backend database and may include directives such as isolation levels, file directives, fetch directives, etc.

.. seealso::

:meth:`_expression.Select.with_hint`

:meth:`_expression.Select.prefix_with` - generic SELECT prefixing
which also can suit some database-specific HINT syntaxes such as
MySQL optimizer hints
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
def with_statement_hint(self, text: str, dialect_name: str = "*") -> Self:
    """Add a statement hint to this :class:`_expression.Select` or
    other selectable object.

    This method is similar to :meth:`_expression.Select.with_hint`
    except that
    it does not require an individual table, and instead applies to the
    statement as a whole.

    Hints here are specific to the backend database and may include
    directives such as isolation levels, file directives, fetch directives,
    etc.

    .. seealso::

        :meth:`_expression.Select.with_hint`

        :meth:`_expression.Select.prefix_with` - generic SELECT prefixing
        which also can suit some database-specific HINT syntaxes such as
        MySQL optimizer hints

    """
    return self._with_hint(None, text, dialect_name)

with_hint

with_hint(
    selectable: _FromClauseArgument,
    text: str,
    dialect_name: str = "*",
) -> Self

Add an indexing or other executional context hint for the given selectable to this :class:_expression.Select or other selectable object.

The text of the hint is rendered in the appropriate location for the database backend in use, relative to the given :class:_schema.Table or :class:_expression.Alias passed as the selectable argument. The dialect implementation typically uses Python string substitution syntax with the token %(name)s to render the name of the table or alias. E.g. when using Oracle, the following::

select(mytable).\
    with_hint(mytable, "index(%(name)s ix_mytable)")

Would render SQL as::

select /*+ index(mytable ix_mytable) */ ... from mytable

The dialect_name option will limit the rendering of a particular hint to a particular backend. Such as, to add hints for both Oracle and Sybase simultaneously::

select(mytable).\
    with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
    with_hint(mytable, "WITH INDEX ix_mytable", 'mssql')

.. seealso::

:meth:`_expression.Select.with_statement_hint`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
@_generative
def with_hint(
    self,
    selectable: _FromClauseArgument,
    text: str,
    dialect_name: str = "*",
) -> Self:
    r"""Add an indexing or other executional context hint for the given
    selectable to this :class:`_expression.Select` or other selectable
    object.

    The text of the hint is rendered in the appropriate
    location for the database backend in use, relative
    to the given :class:`_schema.Table` or :class:`_expression.Alias`
    passed as the
    ``selectable`` argument. The dialect implementation
    typically uses Python string substitution syntax
    with the token ``%(name)s`` to render the name of
    the table or alias. E.g. when using Oracle, the
    following::

        select(mytable).\
            with_hint(mytable, "index(%(name)s ix_mytable)")

    Would render SQL as::

        select /*+ index(mytable ix_mytable) */ ... from mytable

    The ``dialect_name`` option will limit the rendering of a particular
    hint to a particular backend. Such as, to add hints for both Oracle
    and Sybase simultaneously::

        select(mytable).\
            with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
            with_hint(mytable, "WITH INDEX ix_mytable", 'mssql')

    .. seealso::

        :meth:`_expression.Select.with_statement_hint`

    """

    return self._with_hint(selectable, text, dialect_name)

suffix_with

suffix_with(
    *suffixes: _TextCoercedExpressionArgument[Any],
    dialect: str = "*",
) -> Self

Add one or more expressions following the statement as a whole.

This is used to support backend-specific suffix keywords on certain constructs.

E.g.::

stmt = select(col1, col2).cte().suffix_with(
    "cycle empno set y_cycle to 1 default 0", dialect="oracle")

Multiple suffixes can be specified by multiple calls to :meth:_expression.HasSuffixes.suffix_with.

:param *suffixes: textual or :class:_expression.ClauseElement construct which will be rendered following the target clause. :param dialect: Optional string dialect name which will limit rendering of this suffix to only that dialect.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
@_generative
@_document_text_coercion(
    "suffixes",
    ":meth:`_expression.HasSuffixes.suffix_with`",
    ":paramref:`.HasSuffixes.suffix_with.*suffixes`",
)
def suffix_with(
    self,
    *suffixes: _TextCoercedExpressionArgument[Any],
    dialect: str = "*",
) -> Self:
    r"""Add one or more expressions following the statement as a whole.

    This is used to support backend-specific suffix keywords on
    certain constructs.

    E.g.::

        stmt = select(col1, col2).cte().suffix_with(
            "cycle empno set y_cycle to 1 default 0", dialect="oracle")

    Multiple suffixes can be specified by multiple calls
    to :meth:`_expression.HasSuffixes.suffix_with`.

    :param \*suffixes: textual or :class:`_expression.ClauseElement`
     construct which
     will be rendered following the target clause.
    :param dialect: Optional string dialect name which will
     limit rendering of this suffix to only that dialect.

    """
    self._suffixes = self._suffixes + tuple(
        [
            (coercions.expect(roles.StatementOptionRole, p), dialect)
            for p in suffixes
        ]
    )
    return self

prefix_with

prefix_with(
    *prefixes: _TextCoercedExpressionArgument[Any],
    dialect: str = "*",
) -> Self

Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.

This is used to support backend-specific prefix keywords such as those provided by MySQL.

E.g.::

stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

# MySQL 5.7 optimizer hints
stmt = select(table).prefix_with(
    "/*+ BKA(t1) */", dialect="mysql")

Multiple prefixes can be specified by multiple calls to :meth:_expression.HasPrefixes.prefix_with.

:param *prefixes: textual or :class:_expression.ClauseElement construct which will be rendered following the INSERT, UPDATE, or DELETE keyword. :param dialect: optional string dialect name which will limit rendering of this prefix to only that dialect.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
@_generative
@_document_text_coercion(
    "prefixes",
    ":meth:`_expression.HasPrefixes.prefix_with`",
    ":paramref:`.HasPrefixes.prefix_with.*prefixes`",
)
def prefix_with(
    self,
    *prefixes: _TextCoercedExpressionArgument[Any],
    dialect: str = "*",
) -> Self:
    r"""Add one or more expressions following the statement keyword, i.e.
    SELECT, INSERT, UPDATE, or DELETE. Generative.

    This is used to support backend-specific prefix keywords such as those
    provided by MySQL.

    E.g.::

        stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")

        # MySQL 5.7 optimizer hints
        stmt = select(table).prefix_with(
            "/*+ BKA(t1) */", dialect="mysql")

    Multiple prefixes can be specified by multiple calls
    to :meth:`_expression.HasPrefixes.prefix_with`.

    :param \*prefixes: textual or :class:`_expression.ClauseElement`
     construct which
     will be rendered following the INSERT, UPDATE, or DELETE
     keyword.
    :param dialect: optional string dialect name which will
     limit rendering of this prefix to only that dialect.

    """
    self._prefixes = self._prefixes + tuple(
        [
            (coercions.expect(roles.StatementOptionRole, p), dialect)
            for p in prefixes
        ]
    )
    return self

tuples

tuples() -> Query[Tuple[_O]]

return a tuple-typed form of this :class:.Query.

This method invokes the :meth:.Query.only_return_tuples method with a value of True, which by itself ensures that this :class:.Query will always return :class:.Row objects, even if the query is made against a single entity. It then also at the typing level will return a "typed" query, if possible, that will type result rows as Tuple objects with typed elements.

This method can be compared to the :meth:.Result.tuples method, which returns "self", but from a typing perspective returns an object that will yield typed Tuple objects for results. Typing takes effect only if this :class:.Query object is a typed query object already.

.. versionadded:: 2.0

.. seealso::

:meth:`.Result.tuples` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def tuples(self: Query[_O]) -> Query[Tuple[_O]]:
    """return a tuple-typed form of this :class:`.Query`.

    This method invokes the :meth:`.Query.only_return_tuples`
    method with a value of ``True``, which by itself ensures that this
    :class:`.Query` will always return :class:`.Row` objects, even
    if the query is made against a single entity.  It then also
    at the typing level will return a "typed" query, if possible,
    that will type result rows as ``Tuple`` objects with typed
    elements.

    This method can be compared to the :meth:`.Result.tuples` method,
    which returns "self", but from a typing perspective returns an object
    that will yield typed ``Tuple`` objects for results.   Typing
    takes effect only if this :class:`.Query` object is a typed
    query object already.

    .. versionadded:: 2.0

    .. seealso::

        :meth:`.Result.tuples` - v2 equivalent method.

    """
    return self.only_return_tuples(True)  # type: ignore

subquery

subquery(
    name: Optional[str] = None,
    with_labels: bool = False,
    reduce_columns: bool = False,
) -> Subquery

Return the full SELECT statement represented by this :class:_query.Query, embedded within an :class:_expression.Alias.

Eager JOIN generation within the query is disabled.

.. seealso::

:meth:`_sql.Select.subquery` - v2 comparable method.

:param name: string name to be assigned as the alias; this is passed through to :meth:_expression.FromClause.alias. If None, a name will be deterministically generated at compile time.

:param with_labels: if True, :meth:.with_labels will be called on the :class:_query.Query first to apply table-qualified labels to all columns.

:param reduce_columns: if True, :meth:_expression.Select.reduce_columns will be called on the resulting :func:_expression.select construct, to remove same-named columns where one also refers to the other via foreign key or WHERE clause equivalence.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def subquery(
    self,
    name: Optional[str] = None,
    with_labels: bool = False,
    reduce_columns: bool = False,
) -> Subquery:
    """Return the full SELECT statement represented by
    this :class:`_query.Query`, embedded within an
    :class:`_expression.Alias`.

    Eager JOIN generation within the query is disabled.

    .. seealso::

        :meth:`_sql.Select.subquery` - v2 comparable method.

    :param name: string name to be assigned as the alias;
        this is passed through to :meth:`_expression.FromClause.alias`.
        If ``None``, a name will be deterministically generated
        at compile time.

    :param with_labels: if True, :meth:`.with_labels` will be called
     on the :class:`_query.Query` first to apply table-qualified labels
     to all columns.

    :param reduce_columns: if True,
     :meth:`_expression.Select.reduce_columns` will
     be called on the resulting :func:`_expression.select` construct,
     to remove same-named columns where one also refers to the other
     via foreign key or WHERE clause equivalence.

    """
    q = self.enable_eagerloads(False)
    if with_labels:
        q = q.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)

    stmt = q._get_select_statement_only()

    if TYPE_CHECKING:
        assert isinstance(stmt, Select)

    if reduce_columns:
        stmt = stmt.reduce_columns()
    return stmt.subquery(name=name)

cte

cte(
    name: Optional[str] = None,
    recursive: bool = False,
    nesting: bool = False,
) -> CTE

Return the full SELECT statement represented by this :class:_query.Query represented as a common table expression (CTE).

Parameters and usage are the same as those of the :meth:_expression.SelectBase.cte method; see that method for further details.

Here is the PostgreSQL WITH RECURSIVE example <https://www.postgresql.org/docs/current/static/queries-with.html>_. Note that, in this example, the included_parts cte and the incl_alias alias of it are Core selectables, which means the columns are accessed via the .c. attribute. The parts_alias object is an :func:_orm.aliased instance of the Part entity, so column-mapped attributes are available directly::

from sqlalchemy.orm import aliased

class Part(Base):
    __tablename__ = 'part'
    part = Column(String, primary_key=True)
    sub_part = Column(String, primary_key=True)
    quantity = Column(Integer)

included_parts = session.query(
                Part.sub_part,
                Part.part,
                Part.quantity).\
                    filter(Part.part=="our part").\
                    cte(name="included_parts", recursive=True)

incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Part, name="p")
included_parts = included_parts.union_all(
    session.query(
        parts_alias.sub_part,
        parts_alias.part,
        parts_alias.quantity).\
            filter(parts_alias.part==incl_alias.c.sub_part)
    )

q = session.query(
        included_parts.c.sub_part,
        func.sum(included_parts.c.quantity).
            label('total_quantity')
    ).\
    group_by(included_parts.c.sub_part)

.. seealso::

:meth:`_sql.Select.cte` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def cte(
    self,
    name: Optional[str] = None,
    recursive: bool = False,
    nesting: bool = False,
) -> CTE:
    r"""Return the full SELECT statement represented by this
    :class:`_query.Query` represented as a common table expression (CTE).

    Parameters and usage are the same as those of the
    :meth:`_expression.SelectBase.cte` method; see that method for
    further details.

    Here is the `PostgreSQL WITH
    RECURSIVE example
    <https://www.postgresql.org/docs/current/static/queries-with.html>`_.
    Note that, in this example, the ``included_parts`` cte and the
    ``incl_alias`` alias of it are Core selectables, which
    means the columns are accessed via the ``.c.`` attribute.  The
    ``parts_alias`` object is an :func:`_orm.aliased` instance of the
    ``Part`` entity, so column-mapped attributes are available
    directly::

        from sqlalchemy.orm import aliased

        class Part(Base):
            __tablename__ = 'part'
            part = Column(String, primary_key=True)
            sub_part = Column(String, primary_key=True)
            quantity = Column(Integer)

        included_parts = session.query(
                        Part.sub_part,
                        Part.part,
                        Part.quantity).\
                            filter(Part.part=="our part").\
                            cte(name="included_parts", recursive=True)

        incl_alias = aliased(included_parts, name="pr")
        parts_alias = aliased(Part, name="p")
        included_parts = included_parts.union_all(
            session.query(
                parts_alias.sub_part,
                parts_alias.part,
                parts_alias.quantity).\
                    filter(parts_alias.part==incl_alias.c.sub_part)
            )

        q = session.query(
                included_parts.c.sub_part,
                func.sum(included_parts.c.quantity).
                    label('total_quantity')
            ).\
            group_by(included_parts.c.sub_part)

    .. seealso::

        :meth:`_sql.Select.cte` - v2 equivalent method.

    """
    return (
        self.enable_eagerloads(False)
        ._get_select_statement_only()
        .cte(name=name, recursive=recursive, nesting=nesting)
    )

label

label(name: Optional[str]) -> Label[Any]

Return the full SELECT statement represented by this :class:_query.Query, converted to a scalar subquery with a label of the given name.

.. seealso::

:meth:`_sql.Select.label` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def label(self, name: Optional[str]) -> Label[Any]:
    """Return the full SELECT statement represented by this
    :class:`_query.Query`, converted
    to a scalar subquery with a label of the given name.

    .. seealso::

        :meth:`_sql.Select.label` - v2 comparable method.

    """

    return (
        self.enable_eagerloads(False)
        ._get_select_statement_only()
        .label(name)
    )

as_scalar

as_scalar() -> ScalarSelect[_MAYBE_ENTITY]
as_scalar() -> ScalarSelect[_NOT_ENTITY]
as_scalar() -> ScalarSelect[Any]
as_scalar() -> ScalarSelect[Any]

Return the full SELECT statement represented by this :class:_query.Query, converted to a scalar subquery.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.deprecated(
    "1.4",
    "The :meth:`_query.Query.as_scalar` method is deprecated and will be "
    "removed in a future release.  Please refer to "
    ":meth:`_query.Query.scalar_subquery`.",
)
def as_scalar(self) -> ScalarSelect[Any]:
    """Return the full SELECT statement represented by this
    :class:`_query.Query`, converted to a scalar subquery.

    """
    return self.scalar_subquery()

scalar_subquery

scalar_subquery() -> ScalarSelect[Any]
scalar_subquery() -> ScalarSelect[_NOT_ENTITY]
scalar_subquery() -> ScalarSelect[Any]
scalar_subquery() -> ScalarSelect[Any]

Return the full SELECT statement represented by this :class:_query.Query, converted to a scalar subquery.

Analogous to :meth:sqlalchemy.sql.expression.SelectBase.scalar_subquery.

.. versionchanged:: 1.4 The :meth:_query.Query.scalar_subquery method replaces the :meth:_query.Query.as_scalar method.

.. seealso::

:meth:`_sql.Select.scalar_subquery` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def scalar_subquery(self) -> ScalarSelect[Any]:
    """Return the full SELECT statement represented by this
    :class:`_query.Query`, converted to a scalar subquery.

    Analogous to
    :meth:`sqlalchemy.sql.expression.SelectBase.scalar_subquery`.

    .. versionchanged:: 1.4 The :meth:`_query.Query.scalar_subquery`
       method replaces the :meth:`_query.Query.as_scalar` method.

    .. seealso::

        :meth:`_sql.Select.scalar_subquery` - v2 comparable method.

    """

    return (
        self.enable_eagerloads(False)
        ._get_select_statement_only()
        .scalar_subquery()
    )

only_return_tuples

only_return_tuples(
    value: Literal[True],
) -> RowReturningQuery[Tuple[_O]]
only_return_tuples(value: Literal[False]) -> Query[_O]
only_return_tuples(value: bool) -> Query[Any]

When set to True, the query results will always be a :class:.Row object.

This can change a query that normally returns a single entity as a scalar to return a :class:.Row result in all cases.

.. seealso::

:meth:`.Query.tuples` - returns tuples, but also at the typing
level will type results as ``Tuple``.

:meth:`_query.Query.is_single_entity`

:meth:`_engine.Result.tuples` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def only_return_tuples(self, value: bool) -> Query[Any]:
    """When set to True, the query results will always be a
    :class:`.Row` object.

    This can change a query that normally returns a single entity
    as a scalar to return a :class:`.Row` result in all cases.

    .. seealso::

        :meth:`.Query.tuples` - returns tuples, but also at the typing
        level will type results as ``Tuple``.

        :meth:`_query.Query.is_single_entity`

        :meth:`_engine.Result.tuples` - v2 comparable method.

    """
    self.load_options += dict(_only_return_tuples=value)
    return self

enable_eagerloads

enable_eagerloads(value: bool) -> Self

Control whether or not eager joins and subqueries are rendered.

When set to False, the returned Query will not render eager joins regardless of :func:~sqlalchemy.orm.joinedload, :func:~sqlalchemy.orm.subqueryload options or mapper-level lazy='joined'/lazy='subquery' configurations.

This is used primarily when nesting the Query's statement into a subquery or other selectable, or when using :meth:_query.Query.yield_per.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def enable_eagerloads(self, value: bool) -> Self:
    """Control whether or not eager joins and subqueries are
    rendered.

    When set to False, the returned Query will not render
    eager joins regardless of :func:`~sqlalchemy.orm.joinedload`,
    :func:`~sqlalchemy.orm.subqueryload` options
    or mapper-level ``lazy='joined'``/``lazy='subquery'``
    configurations.

    This is used primarily when nesting the Query's
    statement into a subquery or other
    selectable, or when using :meth:`_query.Query.yield_per`.

    """
    self._compile_options += {"_enable_eagerloads": value}
    return self

set_label_style

set_label_style(style: SelectLabelStyle) -> Self

Apply column labels to the return value of Query.statement.

Indicates that this Query's statement accessor should return a SELECT statement that applies labels to all columns in the form _; this is commonly used to disambiguate columns from multiple tables which have the same name.

When the Query actually issues SQL to load rows, it always uses column labeling.

.. note:: The :meth:_query.Query.set_label_style method only applies the output of :attr:_query.Query.statement, and not to any of the result-row invoking systems of :class:_query.Query itself, e.g. :meth:_query.Query.first, :meth:_query.Query.all, etc. To execute a query using :meth:_query.Query.set_label_style, invoke the :attr:_query.Query.statement using :meth:.Session.execute::

    result = session.execute(
        query
        .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
        .statement
    )

.. versionadded:: 1.4

.. seealso::

:meth:`_sql.Select.set_label_style` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def set_label_style(self, style: SelectLabelStyle) -> Self:
    """Apply column labels to the return value of Query.statement.

    Indicates that this Query's `statement` accessor should return
    a SELECT statement that applies labels to all columns in the
    form <tablename>_<columnname>; this is commonly used to
    disambiguate columns from multiple tables which have the same
    name.

    When the `Query` actually issues SQL to load rows, it always
    uses column labeling.

    .. note:: The :meth:`_query.Query.set_label_style` method *only* applies
       the output of :attr:`_query.Query.statement`, and *not* to any of
       the result-row invoking systems of :class:`_query.Query` itself,
       e.g.
       :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc.
       To execute
       a query using :meth:`_query.Query.set_label_style`, invoke the
       :attr:`_query.Query.statement` using :meth:`.Session.execute`::

            result = session.execute(
                query
                .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
                .statement
            )

    .. versionadded:: 1.4


    .. seealso::

        :meth:`_sql.Select.set_label_style` - v2 equivalent method.

    """  # noqa
    if self._label_style is not style:
        self = self._generate()
        self._label_style = style
    return self

enable_assertions

enable_assertions(value: bool) -> Self

Control whether assertions are generated.

When set to False, the returned Query will not assert its state before certain operations, including that LIMIT/OFFSET has not been applied when filter() is called, no criterion exists when get() is called, and no "from_statement()" exists when filter()/order_by()/group_by() etc. is called. This more permissive mode is used by custom Query subclasses to specify criterion or other modifiers outside of the usual usage patterns.

Care should be taken to ensure that the usage pattern is even possible. A statement applied by from_statement() will override any criterion set by filter() or order_by(), for example.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def enable_assertions(self, value: bool) -> Self:
    """Control whether assertions are generated.

    When set to False, the returned Query will
    not assert its state before certain operations,
    including that LIMIT/OFFSET has not been applied
    when filter() is called, no criterion exists
    when get() is called, and no "from_statement()"
    exists when filter()/order_by()/group_by() etc.
    is called.  This more permissive mode is used by
    custom Query subclasses to specify criterion or
    other modifiers outside of the usual usage patterns.

    Care should be taken to ensure that the usage
    pattern is even possible.  A statement applied
    by from_statement() will override any criterion
    set by filter() or order_by(), for example.

    """
    self._enable_assertions = value
    return self

yield_per

yield_per(count: int) -> Self

Yield only count rows at a time.

The purpose of this method is when fetching very large result sets (> 10K rows), to batch results in sub-collections and yield them out partially, so that the Python interpreter doesn't need to declare very large areas of memory which is both time consuming and leads to excessive memory use. The performance from fetching hundreds of thousands of rows can often double when a suitable yield-per setting (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most).

As of SQLAlchemy 1.4, the :meth:_orm.Query.yield_per method is equivalent to using the yield_per execution option at the ORM level. See the section :ref:orm_queryguide_yield_per for further background on this option.

.. seealso::

:ref:`orm_queryguide_yield_per`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def yield_per(self, count: int) -> Self:
    r"""Yield only ``count`` rows at a time.

    The purpose of this method is when fetching very large result sets
    (> 10K rows), to batch results in sub-collections and yield them
    out partially, so that the Python interpreter doesn't need to declare
    very large areas of memory which is both time consuming and leads
    to excessive memory use.   The performance from fetching hundreds of
    thousands of rows can often double when a suitable yield-per setting
    (e.g. approximately 1000) is used, even with DBAPIs that buffer
    rows (which are most).

    As of SQLAlchemy 1.4, the :meth:`_orm.Query.yield_per` method is
    equivalent to using the ``yield_per`` execution option at the ORM
    level. See the section :ref:`orm_queryguide_yield_per` for further
    background on this option.

    .. seealso::

        :ref:`orm_queryguide_yield_per`

    """
    self.load_options += {"_yield_per": count}
    return self

get

get(ident: _PKIdentityArgument) -> Optional[Any]

Return an instance based on the given primary key identifier, or None if not found.

E.g.::

my_user = session.query(User).get(5)

some_object = session.query(VersionedFoo).get((5, 10))

some_object = session.query(VersionedFoo).get(
    {"id": 5, "version_id": 10})

:meth:_query.Query.get is special in that it provides direct access to the identity map of the owning :class:.Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

:meth:_query.Query.get also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, :class:~sqlalchemy.orm.exc.ObjectDeletedError is raised.

:meth:_query.Query.get is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating :class:_query.Query must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via :meth:_query.Query.options may be applied however, and will be used if the object is not yet locally present.

:param ident: A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed.

For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like::

my_object = query.get(5)

The tuple form contains primary key values typically in the order in which they correspond to the mapped :class:_schema.Table object's primary key columns, or if the :paramref:_orm.Mapper.primary_key configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like::

 my_object = query.get((5, 10))

The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes id, version_id as the attributes which store the object's primary key value, the call would look like::

my_object = query.get({"id": 5, "version_id": 10})

.. versionadded:: 1.3 the :meth:_query.Query.get method now optionally accepts a dictionary of attribute names to values in order to indicate a primary key identifier.

:return: The object instance, or None.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.became_legacy_20(
    ":meth:`_orm.Query.get`",
    alternative="The method is now available as :meth:`_orm.Session.get`",
)
def get(self, ident: _PKIdentityArgument) -> Optional[Any]:
    """Return an instance based on the given primary key identifier,
    or ``None`` if not found.

    E.g.::

        my_user = session.query(User).get(5)

        some_object = session.query(VersionedFoo).get((5, 10))

        some_object = session.query(VersionedFoo).get(
            {"id": 5, "version_id": 10})

    :meth:`_query.Query.get` is special in that it provides direct
    access to the identity map of the owning :class:`.Session`.
    If the given primary key identifier is present
    in the local identity map, the object is returned
    directly from this collection and no SQL is emitted,
    unless the object has been marked fully expired.
    If not present,
    a SELECT is performed in order to locate the object.

    :meth:`_query.Query.get` also will perform a check if
    the object is present in the identity map and
    marked as expired - a SELECT
    is emitted to refresh the object as well as to
    ensure that the row is still present.
    If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.

    :meth:`_query.Query.get` is only used to return a single
    mapped instance, not multiple instances or
    individual column constructs, and strictly
    on a single primary key value.  The originating
    :class:`_query.Query` must be constructed in this way,
    i.e. against a single mapped entity,
    with no additional filtering criterion.  Loading
    options via :meth:`_query.Query.options` may be applied
    however, and will be used if the object is not
    yet locally present.

    :param ident: A scalar, tuple, or dictionary representing the
     primary key.  For a composite (e.g. multiple column) primary key,
     a tuple or dictionary should be passed.

     For a single-column primary key, the scalar calling form is typically
     the most expedient.  If the primary key of a row is the value "5",
     the call looks like::

        my_object = query.get(5)

     The tuple form contains primary key values typically in
     the order in which they correspond to the mapped
     :class:`_schema.Table`
     object's primary key columns, or if the
     :paramref:`_orm.Mapper.primary_key` configuration parameter were
     used, in
     the order used for that parameter. For example, if the primary key
     of a row is represented by the integer
     digits "5, 10" the call would look like::

         my_object = query.get((5, 10))

     The dictionary form should include as keys the mapped attribute names
     corresponding to each element of the primary key.  If the mapped class
     has the attributes ``id``, ``version_id`` as the attributes which
     store the object's primary key value, the call would look like::

        my_object = query.get({"id": 5, "version_id": 10})

     .. versionadded:: 1.3 the :meth:`_query.Query.get`
        method now optionally
        accepts a dictionary of attribute names to values in order to
        indicate a primary key identifier.


    :return: The object instance, or ``None``.

    """
    self._no_criterion_assertion("get", order_by=False, distinct=False)

    # we still implement _get_impl() so that baked query can override
    # it
    return self._get_impl(ident, loading.load_on_pk_identity)

correlate

correlate(
    *fromclauses: Union[
        Literal[None, False], _FromClauseArgument
    ],
) -> Self

Return a :class:.Query construct which will correlate the given FROM clauses to that of an enclosing :class:.Query or :func:~.expression.select.

The method here accepts mapped classes, :func:.aliased constructs, and :class:_orm.Mapper constructs as arguments, which are resolved into expression constructs, in addition to appropriate expression constructs.

The correlation arguments are ultimately passed to :meth:_expression.Select.correlate after coercion to expression constructs.

The correlation arguments take effect in such cases as when :meth:_query.Query.from_self is used, or when a subquery as returned by :meth:_query.Query.subquery is embedded in another :func:_expression.select construct.

.. seealso::

:meth:`_sql.Select.correlate` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def correlate(
    self,
    *fromclauses: Union[Literal[None, False], _FromClauseArgument],
) -> Self:
    """Return a :class:`.Query` construct which will correlate the given
    FROM clauses to that of an enclosing :class:`.Query` or
    :func:`~.expression.select`.

    The method here accepts mapped classes, :func:`.aliased` constructs,
    and :class:`_orm.Mapper` constructs as arguments, which are resolved
    into expression constructs, in addition to appropriate expression
    constructs.

    The correlation arguments are ultimately passed to
    :meth:`_expression.Select.correlate`
    after coercion to expression constructs.

    The correlation arguments take effect in such cases
    as when :meth:`_query.Query.from_self` is used, or when
    a subquery as returned by :meth:`_query.Query.subquery` is
    embedded in another :func:`_expression.select` construct.

    .. seealso::

        :meth:`_sql.Select.correlate` - v2 equivalent method.

    """

    self._auto_correlate = False
    if fromclauses and fromclauses[0] in {None, False}:
        self._correlate = ()
    else:
        self._correlate = self._correlate + tuple(
            coercions.expect(roles.FromClauseRole, f) for f in fromclauses
        )
    return self

autoflush

autoflush(setting: bool) -> Self

Return a Query with a specific 'autoflush' setting.

As of SQLAlchemy 1.4, the :meth:_orm.Query.autoflush method is equivalent to using the autoflush execution option at the ORM level. See the section :ref:orm_queryguide_autoflush for further background on this option.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def autoflush(self, setting: bool) -> Self:
    """Return a Query with a specific 'autoflush' setting.

    As of SQLAlchemy 1.4, the :meth:`_orm.Query.autoflush` method
    is equivalent to using the ``autoflush`` execution option at the
    ORM level. See the section :ref:`orm_queryguide_autoflush` for
    further background on this option.

    """
    self.load_options += {"_autoflush": setting}
    return self

populate_existing

populate_existing() -> Self

Return a :class:_query.Query that will expire and refresh all instances as they are loaded, or reused from the current :class:.Session.

As of SQLAlchemy 1.4, the :meth:_orm.Query.populate_existing method is equivalent to using the populate_existing execution option at the ORM level. See the section :ref:orm_queryguide_populate_existing for further background on this option.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def populate_existing(self) -> Self:
    """Return a :class:`_query.Query`
    that will expire and refresh all instances
    as they are loaded, or reused from the current :class:`.Session`.

    As of SQLAlchemy 1.4, the :meth:`_orm.Query.populate_existing` method
    is equivalent to using the ``populate_existing`` execution option at
    the ORM level. See the section :ref:`orm_queryguide_populate_existing`
    for further background on this option.

    """
    self.load_options += {"_populate_existing": True}
    return self

with_parent

with_parent(
    instance: object,
    property: Optional[QueryableAttribute[Any]] = None,
    from_entity: Optional[_ExternalEntityType[Any]] = None,
) -> Self

Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:_orm.relationship() configuration.

The method uses the :func:.with_parent function to generate the clause, the result of which is passed to :meth:_query.Query.filter.

Parameters are the same as :func:.with_parent, with the exception that the given property can be None, in which case a search is performed against this :class:_query.Query object's target mapper.

:param instance: An instance which has some :func:_orm.relationship.

:param property: Class bound attribute which indicates what relationship from the instance should be used to reconcile the parent/child relationship.

:param from_entity: Entity in which to consider as the left side. This defaults to the "zero" entity of the :class:_query.Query itself.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.became_legacy_20(
    ":meth:`_orm.Query.with_parent`",
    alternative="Use the :func:`_orm.with_parent` standalone construct.",
)
@util.preload_module("sqlalchemy.orm.relationships")
def with_parent(
    self,
    instance: object,
    property: Optional[  # noqa: A002
        attributes.QueryableAttribute[Any]
    ] = None,
    from_entity: Optional[_ExternalEntityType[Any]] = None,
) -> Self:
    """Add filtering criterion that relates the given instance
    to a child object or collection, using its attribute state
    as well as an established :func:`_orm.relationship()`
    configuration.

    The method uses the :func:`.with_parent` function to generate
    the clause, the result of which is passed to
    :meth:`_query.Query.filter`.

    Parameters are the same as :func:`.with_parent`, with the exception
    that the given property can be None, in which case a search is
    performed against this :class:`_query.Query` object's target mapper.

    :param instance:
      An instance which has some :func:`_orm.relationship`.

    :param property:
      Class bound attribute which indicates
      what relationship from the instance should be used to reconcile the
      parent/child relationship.

    :param from_entity:
      Entity in which to consider as the left side.  This defaults to the
      "zero" entity of the :class:`_query.Query` itself.

    """
    relationships = util.preloaded.orm_relationships

    if from_entity:
        entity_zero = inspect(from_entity)
    else:
        entity_zero = _legacy_filter_by_entity_zero(self)
    if property is None:
        # TODO: deprecate, property has to be supplied
        mapper = object_mapper(instance)

        for prop in mapper.iterate_properties:
            if (
                isinstance(prop, relationships.RelationshipProperty)
                and prop.mapper is entity_zero.mapper  # type: ignore
            ):
                property = prop  # type: ignore  # noqa: A001
                break
        else:
            raise sa_exc.InvalidRequestError(
                "Could not locate a property which relates instances "
                "of class '%s' to instances of class '%s'"
                % (
                    entity_zero.mapper.class_.__name__,  # type: ignore
                    instance.__class__.__name__,
                )
            )

    return self.filter(
        with_parent(
            instance,
            property,  # type: ignore
            entity_zero.entity,  # type: ignore
        )
    )

add_entity

add_entity(
    entity: _EntityType[Any],
    alias: Optional[Union[Alias, Subquery]] = None,
) -> Query[Any]

add a mapped entity to the list of result columns to be returned.

.. seealso::

:meth:`_sql.Select.add_columns` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def add_entity(
    self,
    entity: _EntityType[Any],
    alias: Optional[Union[Alias, Subquery]] = None,
) -> Query[Any]:
    """add a mapped entity to the list of result columns
    to be returned.

    .. seealso::

        :meth:`_sql.Select.add_columns` - v2 comparable method.
    """

    if alias is not None:
        # TODO: deprecate
        entity = AliasedClass(entity, alias)

    self._raw_columns = list(self._raw_columns)

    self._raw_columns.append(
        coercions.expect(
            roles.ColumnsClauseRole, entity, apply_propagate_attrs=self
        )
    )
    return self

with_session

with_session(session: Session) -> Self

Return a :class:_query.Query that will use the given :class:.Session.

While the :class:_query.Query object is normally instantiated using the :meth:.Session.query method, it is legal to build the :class:_query.Query directly without necessarily using a :class:.Session. Such a :class:_query.Query object, or any :class:_query.Query already associated with a different :class:.Session, can produce a new :class:_query.Query object associated with a target session using this method::

from sqlalchemy.orm import Query

query = Query([MyClass]).filter(MyClass.id == 5)

result = query.with_session(my_session).one()
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def with_session(self, session: Session) -> Self:
    """Return a :class:`_query.Query` that will use the given
    :class:`.Session`.

    While the :class:`_query.Query`
    object is normally instantiated using the
    :meth:`.Session.query` method, it is legal to build the
    :class:`_query.Query`
    directly without necessarily using a :class:`.Session`.  Such a
    :class:`_query.Query` object, or any :class:`_query.Query`
    already associated
    with a different :class:`.Session`, can produce a new
    :class:`_query.Query`
    object associated with a target session using this method::

        from sqlalchemy.orm import Query

        query = Query([MyClass]).filter(MyClass.id == 5)

        result = query.with_session(my_session).one()

    """

    self.session = session
    return self

values

values(
    *columns: _ColumnsClauseArgument[Any],
) -> Iterable[Any]

Return an iterator yielding result tuples corresponding to the given list of columns

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.deprecated(
    "1.4",
    ":meth:`_query.Query.values` "
    "is deprecated and will be removed in a "
    "future release.  Please use :meth:`_query.Query.with_entities`",
)
def values(self, *columns: _ColumnsClauseArgument[Any]) -> Iterable[Any]:
    """Return an iterator yielding result tuples corresponding
    to the given list of columns

    """
    return self._values_no_warn(*columns)

value

value(column: _ColumnExpressionArgument[Any]) -> Any

Return a scalar result corresponding to the given column expression.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.deprecated(
    "1.4",
    ":meth:`_query.Query.value` "
    "is deprecated and will be removed in a "
    "future release.  Please use :meth:`_query.Query.with_entities` "
    "in combination with :meth:`_query.Query.scalar`",
)
def value(self, column: _ColumnExpressionArgument[Any]) -> Any:
    """Return a scalar result corresponding to the given
    column expression.

    """
    try:
        return next(self._values_no_warn(column))[0]  # type: ignore
    except StopIteration:
        return None

with_entities

with_entities(_entity: _EntityType[_O]) -> Query[_O]
with_entities(
    _colexpr: TypedColumnsClauseRole[_T],
) -> RowReturningQuery[Tuple[_T]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
) -> RowReturningQuery[Tuple[_T0, _T1]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
    __ent3: _TypedColumnClauseArgument[_T3],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
    __ent3: _TypedColumnClauseArgument[_T3],
    __ent4: _TypedColumnClauseArgument[_T4],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
    __ent3: _TypedColumnClauseArgument[_T3],
    __ent4: _TypedColumnClauseArgument[_T4],
    __ent5: _TypedColumnClauseArgument[_T5],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
    __ent3: _TypedColumnClauseArgument[_T3],
    __ent4: _TypedColumnClauseArgument[_T4],
    __ent5: _TypedColumnClauseArgument[_T5],
    __ent6: _TypedColumnClauseArgument[_T6],
) -> RowReturningQuery[
    Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]
]
with_entities(
    __ent0: _TypedColumnClauseArgument[_T0],
    __ent1: _TypedColumnClauseArgument[_T1],
    __ent2: _TypedColumnClauseArgument[_T2],
    __ent3: _TypedColumnClauseArgument[_T3],
    __ent4: _TypedColumnClauseArgument[_T4],
    __ent5: _TypedColumnClauseArgument[_T5],
    __ent6: _TypedColumnClauseArgument[_T6],
    __ent7: _TypedColumnClauseArgument[_T7],
) -> RowReturningQuery[
    Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]
]
with_entities(
    *entities: _ColumnsClauseArgument[Any],
) -> Query[Any]
with_entities(
    *entities: _ColumnsClauseArgument[Any], **__kw: Any
) -> Query[Any]

Return a new :class:_query.Query replacing the SELECT list with the given entities.

e.g.::

# Users, filtered on some arbitrary criterion
# and then ordered by related email address
q = session.query(User).\
            join(User.address).\
            filter(User.name.like('%ed%')).\
            order_by(Address.email)

# given *only* User.id==5, Address.email, and 'q', what
# would the *next* User in the result be ?
subq = q.with_entities(Address.email).\
            order_by(None).\
            filter(User.id==5).\
            subquery()
q = q.join((subq, subq.c.email < Address.email)).\
            limit(1)

.. seealso::

:meth:`_sql.Select.with_only_columns` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def with_entities(
    self, *entities: _ColumnsClauseArgument[Any], **__kw: Any
) -> Query[Any]:
    r"""Return a new :class:`_query.Query`
    replacing the SELECT list with the
    given entities.

    e.g.::

        # Users, filtered on some arbitrary criterion
        # and then ordered by related email address
        q = session.query(User).\
                    join(User.address).\
                    filter(User.name.like('%ed%')).\
                    order_by(Address.email)

        # given *only* User.id==5, Address.email, and 'q', what
        # would the *next* User in the result be ?
        subq = q.with_entities(Address.email).\
                    order_by(None).\
                    filter(User.id==5).\
                    subquery()
        q = q.join((subq, subq.c.email < Address.email)).\
                    limit(1)

    .. seealso::

        :meth:`_sql.Select.with_only_columns` - v2 comparable method.
    """
    if __kw:
        raise _no_kw()

    # Query has all the same fields as Select for this operation
    # this could in theory be based on a protocol but not sure if it's
    # worth it
    _MemoizedSelectEntities._generate_for_statement(self)  # type: ignore
    self._set_entities(entities)
    return self

add_columns

add_columns(
    *column: _ColumnExpressionArgument[Any],
) -> Query[Any]

Add one or more column expressions to the list of result columns to be returned.

.. seealso::

:meth:`_sql.Select.add_columns` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def add_columns(
    self, *column: _ColumnExpressionArgument[Any]
) -> Query[Any]:
    """Add one or more column expressions to the list
    of result columns to be returned.

    .. seealso::

        :meth:`_sql.Select.add_columns` - v2 comparable method.
    """

    self._raw_columns = list(self._raw_columns)

    self._raw_columns.extend(
        coercions.expect(
            roles.ColumnsClauseRole,
            c,
            apply_propagate_attrs=self,
            post_inspect=True,
        )
        for c in column
    )
    return self

add_column

add_column(
    column: _ColumnExpressionArgument[Any],
) -> Query[Any]

Add a column expression to the list of result columns to be returned.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.deprecated(
    "1.4",
    ":meth:`_query.Query.add_column` "
    "is deprecated and will be removed in a "
    "future release.  Please use :meth:`_query.Query.add_columns`",
)
def add_column(self, column: _ColumnExpressionArgument[Any]) -> Query[Any]:
    """Add a column expression to the list of result columns to be
    returned.

    """
    return self.add_columns(column)

options

options(*args: ExecutableOption) -> Self

Return a new :class:_query.Query object, applying the given list of mapper options.

Most supplied options regard changing how column- and relationship-mapped attributes are loaded.

.. seealso::

:ref:`loading_columns`

:ref:`relationship_loader_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def options(self, *args: ExecutableOption) -> Self:
    """Return a new :class:`_query.Query` object,
    applying the given list of
    mapper options.

    Most supplied options regard changing how column- and
    relationship-mapped attributes are loaded.

    .. seealso::

        :ref:`loading_columns`

        :ref:`relationship_loader_options`

    """

    opts = tuple(util.flatten_iterator(args))
    if self._compile_options._current_path:
        # opting for lower method overhead for the checks
        for opt in opts:
            if not opt._is_core and opt._is_legacy_option:  # type: ignore
                opt.process_query_conditionally(self)  # type: ignore
    else:
        for opt in opts:
            if not opt._is_core and opt._is_legacy_option:  # type: ignore
                opt.process_query(self)  # type: ignore

    self._with_options += opts
    return self

with_transformation

with_transformation(
    fn: Callable[[Query[Any]], Query[Any]],
) -> Query[Any]

Return a new :class:_query.Query object transformed by the given function.

E.g.::

def filter_something(criterion):
    def transform(q):
        return q.filter(criterion)
    return transform

q = q.with_transformation(filter_something(x==5))

This allows ad-hoc recipes to be created for :class:_query.Query objects.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def with_transformation(
    self, fn: Callable[[Query[Any]], Query[Any]]
) -> Query[Any]:
    """Return a new :class:`_query.Query` object transformed by
    the given function.

    E.g.::

        def filter_something(criterion):
            def transform(q):
                return q.filter(criterion)
            return transform

        q = q.with_transformation(filter_something(x==5))

    This allows ad-hoc recipes to be created for :class:`_query.Query`
    objects.

    """
    return fn(self)

get_execution_options

get_execution_options() -> _ImmutableExecuteOptions

Get the non-SQL options which will take effect during execution.

.. versionadded:: 1.3

.. seealso::

:meth:`_query.Query.execution_options`

:meth:`_sql.Select.get_execution_options` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def get_execution_options(self) -> _ImmutableExecuteOptions:
    """Get the non-SQL options which will take effect during execution.

    .. versionadded:: 1.3

    .. seealso::

        :meth:`_query.Query.execution_options`

        :meth:`_sql.Select.get_execution_options` - v2 comparable method.

    """
    return self._execution_options

execution_options

execution_options(
    *,
    compiled_cache: Optional[CompiledCacheType] = ...,
    logging_token: str = ...,
    isolation_level: IsolationLevel = ...,
    no_parameters: bool = False,
    stream_results: bool = False,
    max_row_buffer: int = ...,
    yield_per: int = ...,
    insertmanyvalues_page_size: int = ...,
    schema_translate_map: Optional[
        SchemaTranslateMapType
    ] = ...,
    populate_existing: bool = False,
    autoflush: bool = False,
    **opt: Any,
) -> Self
execution_options(**opt: Any) -> Self
execution_options(**kwargs: Any) -> Self

Set non-SQL options which take effect during execution.

Options allowed here include all of those accepted by :meth:_engine.Connection.execution_options, as well as a series of ORM specific options:

populate_existing=True - equivalent to using :meth:_orm.Query.populate_existing

autoflush=True|False - equivalent to using :meth:_orm.Query.autoflush

yield_per=<value> - equivalent to using :meth:_orm.Query.yield_per

Note that the stream_results execution option is enabled automatically if the :meth:~sqlalchemy.orm.query.Query.yield_per() method or execution option is used.

.. versionadded:: 1.4 - added ORM options to :meth:_orm.Query.execution_options

The execution options may also be specified on a per execution basis when using :term:2.0 style queries via the :paramref:_orm.Session.execution_options parameter.

.. warning:: The :paramref:_engine.Connection.execution_options.stream_results parameter should not be used at the level of individual ORM statement executions, as the :class:_orm.Session will not track objects from different schema translate maps within a single session. For multiple schema translate maps within the scope of a single :class:_orm.Session, see :ref:examples_sharding.

.. seealso::

:ref:`engine_stream_results`

:meth:`_query.Query.get_execution_options`

:meth:`_sql.Select.execution_options` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def execution_options(self, **kwargs: Any) -> Self:
    """Set non-SQL options which take effect during execution.

    Options allowed here include all of those accepted by
    :meth:`_engine.Connection.execution_options`, as well as a series
    of ORM specific options:

    ``populate_existing=True`` - equivalent to using
    :meth:`_orm.Query.populate_existing`

    ``autoflush=True|False`` - equivalent to using
    :meth:`_orm.Query.autoflush`

    ``yield_per=<value>`` - equivalent to using
    :meth:`_orm.Query.yield_per`

    Note that the ``stream_results`` execution option is enabled
    automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()`
    method or execution option is used.

    .. versionadded:: 1.4 - added ORM options to
       :meth:`_orm.Query.execution_options`

    The execution options may also be specified on a per execution basis
    when using :term:`2.0 style` queries via the
    :paramref:`_orm.Session.execution_options` parameter.

    .. warning:: The
       :paramref:`_engine.Connection.execution_options.stream_results`
       parameter should not be used at the level of individual ORM
       statement executions, as the :class:`_orm.Session` will not track
       objects from different schema translate maps within a single
       session.  For multiple schema translate maps within the scope of a
       single :class:`_orm.Session`, see :ref:`examples_sharding`.


    .. seealso::

        :ref:`engine_stream_results`

        :meth:`_query.Query.get_execution_options`

        :meth:`_sql.Select.execution_options` - v2 equivalent method.

    """
    self._execution_options = self._execution_options.union(kwargs)
    return self

with_for_update

with_for_update(
    *,
    nowait: bool = False,
    read: bool = False,
    of: Optional[_ForUpdateOfArgument] = None,
    skip_locked: bool = False,
    key_share: bool = False,
) -> Self

return a new :class:_query.Query with the specified options for the FOR UPDATE clause.

The behavior of this method is identical to that of :meth:_expression.GenerativeSelect.with_for_update. When called with no arguments, the resulting SELECT statement will have a FOR UPDATE clause appended. When additional arguments are specified, backend-specific options such as FOR UPDATE NOWAIT or LOCK IN SHARE MODE can take effect.

E.g.::

q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)

The above query on a PostgreSQL backend will render like::

SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT

.. warning::

Using ``with_for_update`` in the context of eager loading
relationships is not officially supported or recommended by
SQLAlchemy and may not work with certain queries on various
database backends.  When ``with_for_update`` is successfully used
with a query that involves :func:`_orm.joinedload`, SQLAlchemy will
attempt to emit SQL that locks all involved tables.

.. note:: It is generally a good idea to combine the use of the :meth:_orm.Query.populate_existing method when using the :meth:_orm.Query.with_for_update method. The purpose of :meth:_orm.Query.populate_existing is to force all the data read from the SELECT to be populated into the ORM objects returned, even if these objects are already in the :term:identity map.

.. seealso::

:meth:`_expression.GenerativeSelect.with_for_update`
- Core level method with
full argument and behavioral description.

:meth:`_orm.Query.populate_existing` - overwrites attributes of
objects already loaded in the identity map.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def with_for_update(
    self,
    *,
    nowait: bool = False,
    read: bool = False,
    of: Optional[_ForUpdateOfArgument] = None,
    skip_locked: bool = False,
    key_share: bool = False,
) -> Self:
    """return a new :class:`_query.Query`
    with the specified options for the
    ``FOR UPDATE`` clause.

    The behavior of this method is identical to that of
    :meth:`_expression.GenerativeSelect.with_for_update`.
    When called with no arguments,
    the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause
    appended.  When additional arguments are specified, backend-specific
    options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE``
    can take effect.

    E.g.::

        q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)

    The above query on a PostgreSQL backend will render like::

        SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT

    .. warning::

        Using ``with_for_update`` in the context of eager loading
        relationships is not officially supported or recommended by
        SQLAlchemy and may not work with certain queries on various
        database backends.  When ``with_for_update`` is successfully used
        with a query that involves :func:`_orm.joinedload`, SQLAlchemy will
        attempt to emit SQL that locks all involved tables.

    .. note::  It is generally a good idea to combine the use of the
       :meth:`_orm.Query.populate_existing` method when using the
       :meth:`_orm.Query.with_for_update` method.   The purpose of
       :meth:`_orm.Query.populate_existing` is to force all the data read
       from the SELECT to be populated into the ORM objects returned,
       even if these objects are already in the :term:`identity map`.

    .. seealso::

        :meth:`_expression.GenerativeSelect.with_for_update`
        - Core level method with
        full argument and behavioral description.

        :meth:`_orm.Query.populate_existing` - overwrites attributes of
        objects already loaded in the identity map.

    """  # noqa: E501

    self._for_update_arg = ForUpdateArg(
        read=read,
        nowait=nowait,
        of=of,
        skip_locked=skip_locked,
        key_share=key_share,
    )
    return self

params

params(
    __params: Optional[Dict[str, Any]] = None, **kw: Any
) -> Self

Add values for bind parameters which may have been specified in filter().

Parameters may be specified using *kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that *kwargs is convenient, however some parameter dictionaries contain unicode keys in which case **kwargs cannot be used.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def params(
    self, __params: Optional[Dict[str, Any]] = None, **kw: Any
) -> Self:
    r"""Add values for bind parameters which may have been
    specified in filter().

    Parameters may be specified using \**kwargs, or optionally a single
    dictionary as the first positional argument. The reason for both is
    that \**kwargs is convenient, however some parameter dictionaries
    contain unicode keys in which case \**kwargs cannot be used.

    """
    if __params:
        kw.update(__params)
    self._params = self._params.union(kw)
    return self

where

where(*criterion: _ColumnExpressionArgument[bool]) -> Self

A synonym for :meth:.Query.filter.

.. versionadded:: 1.4

.. seealso::

:meth:`_sql.Select.where` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def where(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
    """A synonym for :meth:`.Query.filter`.

    .. versionadded:: 1.4

    .. seealso::

        :meth:`_sql.Select.where` - v2 equivalent method.

    """
    return self.filter(*criterion)

filter

filter(*criterion: _ColumnExpressionArgument[bool]) -> Self

Apply the given filtering criterion to a copy of this :class:_query.Query, using SQL expressions.

e.g.::

session.query(MyClass).filter(MyClass.name == 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:.and_ function::

session.query(MyClass).\
    filter(MyClass.name == 'some name', MyClass.id > 5)

The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the :func:_expression.text construct.

.. seealso::

:meth:`_query.Query.filter_by` - filter on keyword expressions.

:meth:`_sql.Select.where` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition, _no_limit_offset)
def filter(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
    r"""Apply the given filtering criterion to a copy
    of this :class:`_query.Query`, using SQL expressions.

    e.g.::

        session.query(MyClass).filter(MyClass.name == 'some name')

    Multiple criteria may be specified as comma separated; the effect
    is that they will be joined together using the :func:`.and_`
    function::

        session.query(MyClass).\
            filter(MyClass.name == 'some name', MyClass.id > 5)

    The criterion is any SQL expression object applicable to the
    WHERE clause of a select.   String expressions are coerced
    into SQL expression constructs via the :func:`_expression.text`
    construct.

    .. seealso::

        :meth:`_query.Query.filter_by` - filter on keyword expressions.

        :meth:`_sql.Select.where` - v2 equivalent method.

    """
    for crit in list(criterion):
        crit = coercions.expect(
            roles.WhereHavingRole, crit, apply_propagate_attrs=self
        )

        self._where_criteria += (crit,)
    return self

filter_by

filter_by(**kwargs: Any) -> Self

Apply the given filtering criterion to a copy of this :class:_query.Query, using keyword expressions.

e.g.::

session.query(MyClass).filter_by(name = 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the :func:.and_ function::

session.query(MyClass).\
    filter_by(name = 'some name', id = 5)

The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to :meth:_query.Query.join.

.. seealso::

:meth:`_query.Query.filter` - filter on SQL expressions.

:meth:`_sql.Select.filter_by` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def filter_by(self, **kwargs: Any) -> Self:
    r"""Apply the given filtering criterion to a copy
    of this :class:`_query.Query`, using keyword expressions.

    e.g.::

        session.query(MyClass).filter_by(name = 'some name')

    Multiple criteria may be specified as comma separated; the effect
    is that they will be joined together using the :func:`.and_`
    function::

        session.query(MyClass).\
            filter_by(name = 'some name', id = 5)

    The keyword expressions are extracted from the primary
    entity of the query, or the last entity that was the
    target of a call to :meth:`_query.Query.join`.

    .. seealso::

        :meth:`_query.Query.filter` - filter on SQL expressions.

        :meth:`_sql.Select.filter_by` - v2 comparable method.

    """
    from_entity = self._filter_by_zero()

    clauses = [
        _entity_namespace_key(from_entity, key) == value
        for key, value in kwargs.items()
    ]
    return self.filter(*clauses)

order_by

order_by(
    __first: Union[
        Literal[None, False, NO_ARG],
        _ColumnExpressionOrStrLabelArgument[Any],
    ] = NO_ARG,
    *clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self

Apply one or more ORDER BY criteria to the query and return the newly resulting :class:_query.Query.

e.g.::

q = session.query(Entity).order_by(Entity.id, Entity.name)

Calling this method multiple times is equivalent to calling it once with all the clauses concatenated. All existing ORDER BY criteria may be cancelled by passing None by itself. New ORDER BY criteria may then be added by invoking :meth:_orm.Query.order_by again, e.g.::

# will erase all ORDER BY and ORDER BY new_col alone
q = q.order_by(None).order_by(new_col)

.. seealso::

These sections describe ORDER BY in terms of :term:`2.0 style`
invocation but apply to :class:`_orm.Query` as well:

:ref:`tutorial_order_by` - in the :ref:`unified_tutorial`

:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

:meth:`_sql.Select.order_by` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def order_by(
    self,
    __first: Union[
        Literal[None, False, _NoArg.NO_ARG],
        _ColumnExpressionOrStrLabelArgument[Any],
    ] = _NoArg.NO_ARG,
    *clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self:
    """Apply one or more ORDER BY criteria to the query and return
    the newly resulting :class:`_query.Query`.

    e.g.::

        q = session.query(Entity).order_by(Entity.id, Entity.name)

    Calling this method multiple times is equivalent to calling it once
    with all the clauses concatenated. All existing ORDER BY criteria may
    be cancelled by passing ``None`` by itself.  New ORDER BY criteria may
    then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::

        # will erase all ORDER BY and ORDER BY new_col alone
        q = q.order_by(None).order_by(new_col)

    .. seealso::

        These sections describe ORDER BY in terms of :term:`2.0 style`
        invocation but apply to :class:`_orm.Query` as well:

        :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`

        :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

        :meth:`_sql.Select.order_by` - v2 equivalent method.

    """

    for assertion in (self._no_statement_condition, self._no_limit_offset):
        assertion("order_by")

    if not clauses and (__first is None or __first is False):
        self._order_by_clauses = ()
    elif __first is not _NoArg.NO_ARG:
        criterion = tuple(
            coercions.expect(roles.OrderByRole, clause)
            for clause in (__first,) + clauses
        )
        self._order_by_clauses += criterion

    return self

group_by

group_by(
    __first: Union[
        Literal[None, False, NO_ARG],
        _ColumnExpressionOrStrLabelArgument[Any],
    ] = NO_ARG,
    *clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self

Apply one or more GROUP BY criterion to the query and return the newly resulting :class:_query.Query.

All existing GROUP BY settings can be suppressed by passing None - this will suppress any GROUP BY configured on mappers as well.

.. seealso::

These sections describe GROUP BY in terms of :term:`2.0 style`
invocation but apply to :class:`_orm.Query` as well:

:ref:`tutorial_group_by_w_aggregates` - in the
:ref:`unified_tutorial`

:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

:meth:`_sql.Select.group_by` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
def group_by(
    self,
    __first: Union[
        Literal[None, False, _NoArg.NO_ARG],
        _ColumnExpressionOrStrLabelArgument[Any],
    ] = _NoArg.NO_ARG,
    *clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self:
    """Apply one or more GROUP BY criterion to the query and return
    the newly resulting :class:`_query.Query`.

    All existing GROUP BY settings can be suppressed by
    passing ``None`` - this will suppress any GROUP BY configured
    on mappers as well.

    .. seealso::

        These sections describe GROUP BY in terms of :term:`2.0 style`
        invocation but apply to :class:`_orm.Query` as well:

        :ref:`tutorial_group_by_w_aggregates` - in the
        :ref:`unified_tutorial`

        :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

        :meth:`_sql.Select.group_by` - v2 equivalent method.

    """

    for assertion in (self._no_statement_condition, self._no_limit_offset):
        assertion("group_by")

    if not clauses and (__first is None or __first is False):
        self._group_by_clauses = ()
    elif __first is not _NoArg.NO_ARG:
        criterion = tuple(
            coercions.expect(roles.GroupByRole, clause)
            for clause in (__first,) + clauses
        )
        self._group_by_clauses += criterion
    return self

having

having(*having: _ColumnExpressionArgument[bool]) -> Self

Apply a HAVING criterion to the query and return the newly resulting :class:_query.Query.

:meth:_query.Query.having is used in conjunction with :meth:_query.Query.group_by.

HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.::

q = session.query(User.id).\
            join(User.addresses).\
            group_by(User.id).\
            having(func.count(Address.id) > 2)

.. seealso::

:meth:`_sql.Select.having` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition, _no_limit_offset)
def having(self, *having: _ColumnExpressionArgument[bool]) -> Self:
    r"""Apply a HAVING criterion to the query and return the
    newly resulting :class:`_query.Query`.

    :meth:`_query.Query.having` is used in conjunction with
    :meth:`_query.Query.group_by`.

    HAVING criterion makes it possible to use filters on aggregate
    functions like COUNT, SUM, AVG, MAX, and MIN, eg.::

        q = session.query(User.id).\
                    join(User.addresses).\
                    group_by(User.id).\
                    having(func.count(Address.id) > 2)

    .. seealso::

        :meth:`_sql.Select.having` - v2 equivalent method.

    """

    for criterion in having:
        having_criteria = coercions.expect(
            roles.WhereHavingRole, criterion
        )
        self._having_criteria += (having_criteria,)
    return self

union

union(*q: Query[Any]) -> Self

Produce a UNION of this Query against one or more queries.

e.g.::

q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')

q3 = q1.union(q2)

The method accepts multiple Query objects so as to control the level of nesting. A series of union() calls such as::

x.union(y).union(z).all()

will nest on each union(), and produces::

SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION
                SELECT * FROM y) UNION SELECT * FROM Z)

Whereas::

x.union(y, z).all()

produces::

SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION
                SELECT * FROM Z)

Note that many database backends do not allow ORDER BY to be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue query.order_by(None) - the resulting :class:_query.Query object will not render ORDER BY within its SELECT statement.

.. seealso::

:meth:`_sql.Select.union` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def union(self, *q: Query[Any]) -> Self:
    """Produce a UNION of this Query against one or more queries.

    e.g.::

        q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
        q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')

        q3 = q1.union(q2)

    The method accepts multiple Query objects so as to control
    the level of nesting.  A series of ``union()`` calls such as::

        x.union(y).union(z).all()

    will nest on each ``union()``, and produces::

        SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION
                        SELECT * FROM y) UNION SELECT * FROM Z)

    Whereas::

        x.union(y, z).all()

    produces::

        SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION
                        SELECT * FROM Z)

    Note that many database backends do not allow ORDER BY to
    be rendered on a query called within UNION, EXCEPT, etc.
    To disable all ORDER BY clauses including those configured
    on mappers, issue ``query.order_by(None)`` - the resulting
    :class:`_query.Query` object will not render ORDER BY within
    its SELECT statement.

    .. seealso::

        :meth:`_sql.Select.union` - v2 equivalent method.

    """
    return self._set_op(expression.union, *q)

union_all

union_all(*q: Query[Any]) -> Self

Produce a UNION ALL of this Query against one or more queries.

Works the same way as :meth:~sqlalchemy.orm.query.Query.union. See that method for usage examples.

.. seealso::

:meth:`_sql.Select.union_all` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def union_all(self, *q: Query[Any]) -> Self:
    """Produce a UNION ALL of this Query against one or more queries.

    Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
    that method for usage examples.

    .. seealso::

        :meth:`_sql.Select.union_all` - v2 equivalent method.

    """
    return self._set_op(expression.union_all, *q)

intersect

intersect(*q: Query[Any]) -> Self

Produce an INTERSECT of this Query against one or more queries.

Works the same way as :meth:~sqlalchemy.orm.query.Query.union. See that method for usage examples.

.. seealso::

:meth:`_sql.Select.intersect` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def intersect(self, *q: Query[Any]) -> Self:
    """Produce an INTERSECT of this Query against one or more queries.

    Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
    that method for usage examples.

    .. seealso::

        :meth:`_sql.Select.intersect` - v2 equivalent method.

    """
    return self._set_op(expression.intersect, *q)

intersect_all

intersect_all(*q: Query[Any]) -> Self

Produce an INTERSECT ALL of this Query against one or more queries.

Works the same way as :meth:~sqlalchemy.orm.query.Query.union. See that method for usage examples.

.. seealso::

:meth:`_sql.Select.intersect_all` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def intersect_all(self, *q: Query[Any]) -> Self:
    """Produce an INTERSECT ALL of this Query against one or more queries.

    Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
    that method for usage examples.

    .. seealso::

        :meth:`_sql.Select.intersect_all` - v2 equivalent method.

    """
    return self._set_op(expression.intersect_all, *q)

except_

except_(*q: Query[Any]) -> Self

Produce an EXCEPT of this Query against one or more queries.

Works the same way as :meth:~sqlalchemy.orm.query.Query.union. See that method for usage examples.

.. seealso::

:meth:`_sql.Select.except_` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def except_(self, *q: Query[Any]) -> Self:
    """Produce an EXCEPT of this Query against one or more queries.

    Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
    that method for usage examples.

    .. seealso::

        :meth:`_sql.Select.except_` - v2 equivalent method.

    """
    return self._set_op(expression.except_, *q)

except_all

except_all(*q: Query[Any]) -> Self

Produce an EXCEPT ALL of this Query against one or more queries.

Works the same way as :meth:~sqlalchemy.orm.query.Query.union. See that method for usage examples.

.. seealso::

:meth:`_sql.Select.except_all` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def except_all(self, *q: Query[Any]) -> Self:
    """Produce an EXCEPT ALL of this Query against one or more queries.

    Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
    that method for usage examples.

    .. seealso::

        :meth:`_sql.Select.except_all` - v2 equivalent method.

    """
    return self._set_op(expression.except_all, *q)

join

join(
    target: _JoinTargetArgument,
    onclause: Optional[_OnClauseArgument] = None,
    *,
    isouter: bool = False,
    full: bool = False,
) -> Self

Create a SQL JOIN against this :class:_query.Query object's criterion and apply generatively, returning the newly resulting :class:_query.Query.

Simple Relationship Joins

Consider a mapping between two classes User and Address, with a relationship User.addresses representing a collection of Address objects associated with each User. The most common usage of :meth:_query.Query.join is to create a JOIN along this relationship, using the User.addresses attribute as an indicator for how this should occur::

q = session.query(User).join(User.addresses)

Where above, the call to :meth:_query.Query.join along User.addresses will result in SQL approximately equivalent to::

SELECT user.id, user.name
FROM user JOIN address ON user.id = address.user_id

In the above example we refer to User.addresses as passed to :meth:_query.Query.join as the "on clause", that is, it indicates how the "ON" portion of the JOIN should be constructed.

To construct a chain of joins, multiple :meth:_query.Query.join calls may be used. The relationship-bound attribute implies both the left and right side of the join at once::

q = session.query(User).\
        join(User.orders).\
        join(Order.items).\
        join(Item.keywords)

.. note:: as seen in the above example, the order in which each call to the join() method occurs is important. Query would not, for example, know how to join correctly if we were to specify User, then Item, then Order, in our chain of joins; in such a case, depending on the arguments passed, it may raise an error that it doesn't know how to join, or it may produce invalid SQL in which case the database will raise an error. In correct practice, the :meth:_query.Query.join method is invoked in such a way that lines up with how we would want the JOIN clauses in SQL to be rendered, and each call should represent a clear link from what precedes it.

Joins to a Target Entity or Selectable

A second form of :meth:_query.Query.join allows any mapped entity or core selectable construct as a target. In this usage, :meth:_query.Query.join will attempt to create a JOIN along the natural foreign key relationship between two entities::

q = session.query(User).join(Address)

In the above calling form, :meth:_query.Query.join is called upon to create the "on clause" automatically for us. This calling form will ultimately raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between the target entity and the entity or entities already present on the left side such that creating a join requires more information. Note that when indicating a join to a target without any ON clause, ORM configured relationships are not taken into account.

Joins to a Target with an ON Clause

The third calling form allows both the target entity as well as the ON clause to be passed explicitly. A example that includes a SQL expression as the ON clause is as follows::

q = session.query(User).join(Address, User.id==Address.user_id)

The above form may also use a relationship-bound attribute as the ON clause as well::

q = session.query(User).join(Address, User.addresses)

The above syntax can be useful for the case where we wish to join to an alias of a particular target entity. If we wanted to join to Address twice, it could be achieved using two aliases set up using the :func:~sqlalchemy.orm.aliased function::

a1 = aliased(Address)
a2 = aliased(Address)

q = session.query(User).\
        join(a1, User.addresses).\
        join(a2, User.addresses).\
        filter(a1.email_address=='ed@foo.com').\
        filter(a2.email_address=='ed@bar.com')

The relationship-bound calling form can also specify a target entity using the :meth:_orm.PropComparator.of_type method; a query equivalent to the one above would be::

a1 = aliased(Address)
a2 = aliased(Address)

q = session.query(User).\
        join(User.addresses.of_type(a1)).\
        join(User.addresses.of_type(a2)).\
        filter(a1.email_address == 'ed@foo.com').\
        filter(a2.email_address == 'ed@bar.com')

Augmenting Built-in ON Clauses

As a substitute for providing a full custom ON condition for an existing relationship, the :meth:_orm.PropComparator.and_ function may be applied to a relationship attribute to augment additional criteria into the ON clause; the additional criteria will be combined with the default criteria using AND::

q = session.query(User).join(
    User.addresses.and_(Address.email_address != 'foo@bar.com')
)

.. versionadded:: 1.4

Joining to Tables and Subqueries

The target of a join may also be any table or SELECT statement, which may be related to a target entity or not. Use the appropriate .subquery() method in order to make a subquery out of a query::

subq = session.query(Address).\
    filter(Address.email_address == 'ed@foo.com').\
    subquery()


q = session.query(User).join(
    subq, User.id == subq.c.user_id
)

Joining to a subquery in terms of a specific relationship and/or target entity may be achieved by linking the subquery to the entity using :func:_orm.aliased::

subq = session.query(Address).\
    filter(Address.email_address == 'ed@foo.com').\
    subquery()

address_subq = aliased(Address, subq)

q = session.query(User).join(
    User.addresses.of_type(address_subq)
)

Controlling what to Join From

In cases where the left side of the current state of :class:_query.Query is not in line with what we want to join from, the :meth:_query.Query.select_from method may be used::

q = session.query(Address).select_from(User).\
                join(User.addresses).\
                filter(User.name == 'ed')

Which will produce SQL similar to::

SELECT address.* FROM user
    JOIN address ON user.id=address.user_id
    WHERE user.name = :name_1

.. seealso::

:meth:`_sql.Select.join` - v2 equivalent method.

:param *props: Incoming arguments for :meth:_query.Query.join, the props collection in modern use should be considered to be a one or two argument form, either as a single "target" entity or ORM attribute-bound relationship, or as a target entity plus an "on clause" which may be a SQL expression or ORM attribute-bound relationship.

:param isouter=False: If True, the join used will be a left outer join, just as if the :meth:_query.Query.outerjoin method were called.

:param full=False: render FULL OUTER JOIN; implies isouter.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition, _no_limit_offset)
def join(
    self,
    target: _JoinTargetArgument,
    onclause: Optional[_OnClauseArgument] = None,
    *,
    isouter: bool = False,
    full: bool = False,
) -> Self:
    r"""Create a SQL JOIN against this :class:`_query.Query`
    object's criterion
    and apply generatively, returning the newly resulting
    :class:`_query.Query`.

    **Simple Relationship Joins**

    Consider a mapping between two classes ``User`` and ``Address``,
    with a relationship ``User.addresses`` representing a collection
    of ``Address`` objects associated with each ``User``.   The most
    common usage of :meth:`_query.Query.join`
    is to create a JOIN along this
    relationship, using the ``User.addresses`` attribute as an indicator
    for how this should occur::

        q = session.query(User).join(User.addresses)

    Where above, the call to :meth:`_query.Query.join` along
    ``User.addresses`` will result in SQL approximately equivalent to::

        SELECT user.id, user.name
        FROM user JOIN address ON user.id = address.user_id

    In the above example we refer to ``User.addresses`` as passed to
    :meth:`_query.Query.join` as the "on clause", that is, it indicates
    how the "ON" portion of the JOIN should be constructed.

    To construct a chain of joins, multiple :meth:`_query.Query.join`
    calls may be used.  The relationship-bound attribute implies both
    the left and right side of the join at once::

        q = session.query(User).\
                join(User.orders).\
                join(Order.items).\
                join(Item.keywords)

    .. note:: as seen in the above example, **the order in which each
       call to the join() method occurs is important**.    Query would not,
       for example, know how to join correctly if we were to specify
       ``User``, then ``Item``, then ``Order``, in our chain of joins; in
       such a case, depending on the arguments passed, it may raise an
       error that it doesn't know how to join, or it may produce invalid
       SQL in which case the database will raise an error. In correct
       practice, the
       :meth:`_query.Query.join` method is invoked in such a way that lines
       up with how we would want the JOIN clauses in SQL to be
       rendered, and each call should represent a clear link from what
       precedes it.

    **Joins to a Target Entity or Selectable**

    A second form of :meth:`_query.Query.join` allows any mapped entity or
    core selectable construct as a target.   In this usage,
    :meth:`_query.Query.join` will attempt to create a JOIN along the
    natural foreign key relationship between two entities::

        q = session.query(User).join(Address)

    In the above calling form, :meth:`_query.Query.join` is called upon to
    create the "on clause" automatically for us.  This calling form will
    ultimately raise an error if either there are no foreign keys between
    the two entities, or if there are multiple foreign key linkages between
    the target entity and the entity or entities already present on the
    left side such that creating a join requires more information.  Note
    that when indicating a join to a target without any ON clause, ORM
    configured relationships are not taken into account.

    **Joins to a Target with an ON Clause**

    The third calling form allows both the target entity as well
    as the ON clause to be passed explicitly.    A example that includes
    a SQL expression as the ON clause is as follows::

        q = session.query(User).join(Address, User.id==Address.user_id)

    The above form may also use a relationship-bound attribute as the
    ON clause as well::

        q = session.query(User).join(Address, User.addresses)

    The above syntax can be useful for the case where we wish
    to join to an alias of a particular target entity.  If we wanted
    to join to ``Address`` twice, it could be achieved using two
    aliases set up using the :func:`~sqlalchemy.orm.aliased` function::

        a1 = aliased(Address)
        a2 = aliased(Address)

        q = session.query(User).\
                join(a1, User.addresses).\
                join(a2, User.addresses).\
                filter(a1.email_address=='ed@foo.com').\
                filter(a2.email_address=='ed@bar.com')

    The relationship-bound calling form can also specify a target entity
    using the :meth:`_orm.PropComparator.of_type` method; a query
    equivalent to the one above would be::

        a1 = aliased(Address)
        a2 = aliased(Address)

        q = session.query(User).\
                join(User.addresses.of_type(a1)).\
                join(User.addresses.of_type(a2)).\
                filter(a1.email_address == 'ed@foo.com').\
                filter(a2.email_address == 'ed@bar.com')

    **Augmenting Built-in ON Clauses**

    As a substitute for providing a full custom ON condition for an
    existing relationship, the :meth:`_orm.PropComparator.and_` function
    may be applied to a relationship attribute to augment additional
    criteria into the ON clause; the additional criteria will be combined
    with the default criteria using AND::

        q = session.query(User).join(
            User.addresses.and_(Address.email_address != 'foo@bar.com')
        )

    .. versionadded:: 1.4

    **Joining to Tables and Subqueries**


    The target of a join may also be any table or SELECT statement,
    which may be related to a target entity or not.   Use the
    appropriate ``.subquery()`` method in order to make a subquery
    out of a query::

        subq = session.query(Address).\
            filter(Address.email_address == 'ed@foo.com').\
            subquery()


        q = session.query(User).join(
            subq, User.id == subq.c.user_id
        )

    Joining to a subquery in terms of a specific relationship and/or
    target entity may be achieved by linking the subquery to the
    entity using :func:`_orm.aliased`::

        subq = session.query(Address).\
            filter(Address.email_address == 'ed@foo.com').\
            subquery()

        address_subq = aliased(Address, subq)

        q = session.query(User).join(
            User.addresses.of_type(address_subq)
        )


    **Controlling what to Join From**

    In cases where the left side of the current state of
    :class:`_query.Query` is not in line with what we want to join from,
    the :meth:`_query.Query.select_from` method may be used::

        q = session.query(Address).select_from(User).\
                        join(User.addresses).\
                        filter(User.name == 'ed')

    Which will produce SQL similar to::

        SELECT address.* FROM user
            JOIN address ON user.id=address.user_id
            WHERE user.name = :name_1

    .. seealso::

        :meth:`_sql.Select.join` - v2 equivalent method.

    :param \*props: Incoming arguments for :meth:`_query.Query.join`,
     the props collection in modern use should be considered to be a  one
     or two argument form, either as a single "target" entity or ORM
     attribute-bound relationship, or as a target entity plus an "on
     clause" which  may be a SQL expression or ORM attribute-bound
     relationship.

    :param isouter=False: If True, the join used will be a left outer join,
     just as if the :meth:`_query.Query.outerjoin` method were called.

    :param full=False: render FULL OUTER JOIN; implies ``isouter``.

    """

    join_target = coercions.expect(
        roles.JoinTargetRole,
        target,
        apply_propagate_attrs=self,
        legacy=True,
    )
    if onclause is not None:
        onclause_element = coercions.expect(
            roles.OnClauseRole, onclause, legacy=True
        )
    else:
        onclause_element = None

    self._setup_joins += (
        (
            join_target,
            onclause_element,
            None,
            {
                "isouter": isouter,
                "full": full,
            },
        ),
    )

    self.__dict__.pop("_last_joined_entity", None)
    return self

outerjoin

outerjoin(
    target: _JoinTargetArgument,
    onclause: Optional[_OnClauseArgument] = None,
    *,
    full: bool = False,
) -> Self

Create a left outer join against this Query object's criterion and apply generatively, returning the newly resulting Query.

Usage is the same as the join() method.

.. seealso::

:meth:`_sql.Select.outerjoin` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def outerjoin(
    self,
    target: _JoinTargetArgument,
    onclause: Optional[_OnClauseArgument] = None,
    *,
    full: bool = False,
) -> Self:
    """Create a left outer join against this ``Query`` object's criterion
    and apply generatively, returning the newly resulting ``Query``.

    Usage is the same as the ``join()`` method.

    .. seealso::

        :meth:`_sql.Select.outerjoin` - v2 equivalent method.

    """
    return self.join(target, onclause=onclause, isouter=True, full=full)

reset_joinpoint

reset_joinpoint() -> Self

Return a new :class:.Query, where the "join point" has been reset back to the base FROM entities of the query.

This method is usually used in conjunction with the aliased=True feature of the :meth:~.Query.join method. See the example in :meth:~.Query.join for how this is used.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition)
def reset_joinpoint(self) -> Self:
    """Return a new :class:`.Query`, where the "join point" has
    been reset back to the base FROM entities of the query.

    This method is usually used in conjunction with the
    ``aliased=True`` feature of the :meth:`~.Query.join`
    method.  See the example in :meth:`~.Query.join` for how
    this is used.

    """
    self._last_joined_entity = None

    return self

select_from

select_from(*from_obj: _FromClauseArgument) -> Self

Set the FROM clause of this :class:.Query explicitly.

:meth:.Query.select_from is often used in conjunction with :meth:.Query.join in order to control which entity is selected from on the "left" side of the join.

The entity or selectable object here effectively replaces the "left edge" of any calls to :meth:~.Query.join, when no joinpoint is otherwise established - usually, the default "join point" is the leftmost entity in the :class:~.Query object's list of entities to be selected.

A typical example::

q = session.query(Address).select_from(User).\
    join(User.addresses).\
    filter(User.name == 'ed')

Which produces SQL equivalent to::

SELECT address.* FROM user
JOIN address ON user.id=address.user_id
WHERE user.name = :name_1

:param *from_obj: collection of one or more entities to apply to the FROM clause. Entities can be mapped classes, :class:.AliasedClass objects, :class:.Mapper objects as well as core :class:.FromClause elements like subqueries.

.. seealso::

:meth:`~.Query.join`

:meth:`.Query.select_entity_from`

:meth:`_sql.Select.select_from` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_clauseelement_condition)
def select_from(self, *from_obj: _FromClauseArgument) -> Self:
    r"""Set the FROM clause of this :class:`.Query` explicitly.

    :meth:`.Query.select_from` is often used in conjunction with
    :meth:`.Query.join` in order to control which entity is selected
    from on the "left" side of the join.

    The entity or selectable object here effectively replaces the
    "left edge" of any calls to :meth:`~.Query.join`, when no
    joinpoint is otherwise established - usually, the default "join
    point" is the leftmost entity in the :class:`~.Query` object's
    list of entities to be selected.

    A typical example::

        q = session.query(Address).select_from(User).\
            join(User.addresses).\
            filter(User.name == 'ed')

    Which produces SQL equivalent to::

        SELECT address.* FROM user
        JOIN address ON user.id=address.user_id
        WHERE user.name = :name_1

    :param \*from_obj: collection of one or more entities to apply
     to the FROM clause.  Entities can be mapped classes,
     :class:`.AliasedClass` objects, :class:`.Mapper` objects
     as well as core :class:`.FromClause` elements like subqueries.

    .. seealso::

        :meth:`~.Query.join`

        :meth:`.Query.select_entity_from`

        :meth:`_sql.Select.select_from` - v2 equivalent method.

    """

    self._set_select_from(from_obj, False)
    return self

slice

slice(start: int, stop: int) -> Self

Computes the "slice" of the :class:_query.Query represented by the given indices and returns the resulting :class:_query.Query.

The start and stop indices behave like the argument to Python's built-in :func:range function. This method provides an alternative to using LIMIT/OFFSET to get a slice of the query.

For example, ::

session.query(User).order_by(User.id).slice(1, 3)

renders as

.. sourcecode:: sql

SELECT users.id AS users_id, users.name AS users_name FROM users ORDER BY users.id LIMIT ? OFFSET ? (2, 1)

.. seealso::

:meth:_query.Query.limit

:meth:_query.Query.offset

:meth:_sql.Select.slice - v2 equivalent method.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition)
def slice(
    self,
    start: int,
    stop: int,
) -> Self:
    """Computes the "slice" of the :class:`_query.Query` represented by
    the given indices and returns the resulting :class:`_query.Query`.

    The start and stop indices behave like the argument to Python's
    built-in :func:`range` function. This method provides an
    alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
    query.

    For example, ::

        session.query(User).order_by(User.id).slice(1, 3)

    renders as

    .. sourcecode:: sql

       SELECT users.id AS users_id,
              users.name AS users_name
       FROM users ORDER BY users.id
       LIMIT ? OFFSET ?
       (2, 1)

    .. seealso::

       :meth:`_query.Query.limit`

       :meth:`_query.Query.offset`

       :meth:`_sql.Select.slice` - v2 equivalent method.

    """

    self._limit_clause, self._offset_clause = sql_util._make_slice(
        self._limit_clause, self._offset_clause, start, stop
    )
    return self

limit

limit(limit: _LimitOffsetType) -> Self

Apply a LIMIT to the query and return the newly resulting Query.

.. seealso::

:meth:`_sql.Select.limit` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition)
def limit(self, limit: _LimitOffsetType) -> Self:
    """Apply a ``LIMIT`` to the query and return the newly resulting
    ``Query``.

    .. seealso::

        :meth:`_sql.Select.limit` - v2 equivalent method.

    """
    self._limit_clause = sql_util._offset_or_limit_clause(limit)
    return self

offset

offset(offset: _LimitOffsetType) -> Self

Apply an OFFSET to the query and return the newly resulting Query.

.. seealso::

:meth:`_sql.Select.offset` - v2 equivalent method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition)
def offset(self, offset: _LimitOffsetType) -> Self:
    """Apply an ``OFFSET`` to the query and return the newly resulting
    ``Query``.

    .. seealso::

        :meth:`_sql.Select.offset` - v2 equivalent method.
    """
    self._offset_clause = sql_util._offset_or_limit_clause(offset)
    return self

distinct

distinct(*expr: _ColumnExpressionArgument[Any]) -> Self

Apply a DISTINCT to the query and return the newly resulting Query.

.. note::

The ORM-level :meth:`.distinct` call includes logic that will
automatically add columns from the ORDER BY of the query to the
columns clause of the SELECT statement, to satisfy the common need
of the database backend that ORDER BY columns be part of the SELECT
list when DISTINCT is used.   These columns *are not* added to the
list of columns actually fetched by the :class:`_query.Query`,
however,
so would not affect results. The columns are passed through when
using the :attr:`_query.Query.statement` accessor, however.

.. deprecated:: 2.0  This logic is deprecated and will be removed
   in SQLAlchemy 2.0.     See :ref:`migration_20_query_distinct`
   for a description of this use case in 2.0.

.. seealso::

:meth:`_sql.Select.distinct` - v2 equivalent method.

:param *expr: optional column expressions. When present, the PostgreSQL dialect will render a DISTINCT ON (<expressions>) construct.

.. deprecated:: 1.4 Using *expr in other dialects is deprecated and will raise :class:_exc.CompileError in a future version.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_statement_condition)
def distinct(self, *expr: _ColumnExpressionArgument[Any]) -> Self:
    r"""Apply a ``DISTINCT`` to the query and return the newly resulting
    ``Query``.


    .. note::

        The ORM-level :meth:`.distinct` call includes logic that will
        automatically add columns from the ORDER BY of the query to the
        columns clause of the SELECT statement, to satisfy the common need
        of the database backend that ORDER BY columns be part of the SELECT
        list when DISTINCT is used.   These columns *are not* added to the
        list of columns actually fetched by the :class:`_query.Query`,
        however,
        so would not affect results. The columns are passed through when
        using the :attr:`_query.Query.statement` accessor, however.

        .. deprecated:: 2.0  This logic is deprecated and will be removed
           in SQLAlchemy 2.0.     See :ref:`migration_20_query_distinct`
           for a description of this use case in 2.0.

    .. seealso::

        :meth:`_sql.Select.distinct` - v2 equivalent method.

    :param \*expr: optional column expressions.  When present,
     the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
     construct.

     .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
        and will raise :class:`_exc.CompileError` in a future version.

    """
    if expr:
        self._distinct = True
        self._distinct_on = self._distinct_on + tuple(
            coercions.expect(roles.ByOfRole, e) for e in expr
        )
    else:
        self._distinct = True
    return self

all

all() -> List[_T]

Return the results represented by this :class:_query.Query as a list.

This results in an execution of the underlying SQL statement.

.. warning:: The :class:_query.Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key. See the FAQ for more details.

.. seealso::

    :ref:`faq_query_deduplicating`

.. seealso::

:meth:`_engine.Result.all` - v2 comparable method.

:meth:`_engine.Result.scalars` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def all(self) -> List[_T]:
    """Return the results represented by this :class:`_query.Query`
    as a list.

    This results in an execution of the underlying SQL statement.

    .. warning::  The :class:`_query.Query` object,
       when asked to return either
       a sequence or iterator that consists of full ORM-mapped entities,
       will **deduplicate entries based on primary key**.  See the FAQ for
       more details.

        .. seealso::

            :ref:`faq_query_deduplicating`

    .. seealso::

        :meth:`_engine.Result.all` - v2 comparable method.

        :meth:`_engine.Result.scalars` - v2 comparable method.
    """
    return self._iter().all()  # type: ignore

from_statement

from_statement(statement: ExecutableReturnsRows) -> Self

Execute the given SELECT statement and return results.

This method bypasses all internal statement compilation, and the statement is executed without modification.

The statement is typically either a :func:_expression.text or :func:_expression.select construct, and should return the set of columns appropriate to the entity class represented by this :class:_query.Query.

.. seealso::

:meth:`_sql.Select.from_statement` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@_generative
@_assertions(_no_clauseelement_condition)
def from_statement(self, statement: ExecutableReturnsRows) -> Self:
    """Execute the given SELECT statement and return results.

    This method bypasses all internal statement compilation, and the
    statement is executed without modification.

    The statement is typically either a :func:`_expression.text`
    or :func:`_expression.select` construct, and should return the set
    of columns
    appropriate to the entity class represented by this
    :class:`_query.Query`.

    .. seealso::

        :meth:`_sql.Select.from_statement` - v2 comparable method.

    """
    statement = coercions.expect(
        roles.SelectStatementRole, statement, apply_propagate_attrs=self
    )
    self._statement = statement
    return self

first

first() -> Optional[_T]

Return the first result of this Query or None if the result doesn't contain any row.

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

Calling :meth:_query.Query.first results in an execution of the underlying query.

.. seealso::

:meth:`_query.Query.one`

:meth:`_query.Query.one_or_none`

:meth:`_engine.Result.first` - v2 comparable method.

:meth:`_engine.Result.scalars` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def first(self) -> Optional[_T]:
    """Return the first result of this ``Query`` or
    None if the result doesn't contain any row.

    first() applies a limit of one within the generated SQL, so that
    only one primary entity row is generated on the server side
    (note this may consist of multiple result rows if join-loaded
    collections are present).

    Calling :meth:`_query.Query.first`
    results in an execution of the underlying
    query.

    .. seealso::

        :meth:`_query.Query.one`

        :meth:`_query.Query.one_or_none`

        :meth:`_engine.Result.first` - v2 comparable method.

        :meth:`_engine.Result.scalars` - v2 comparable method.

    """
    # replicates limit(1) behavior
    if self._statement is not None:
        return self._iter().first()  # type: ignore
    else:
        return self.limit(1)._iter().first()  # type: ignore

one_or_none

one_or_none() -> Optional[_T]

Return at most one result or raise an exception.

Returns None if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

Calling :meth:_query.Query.one_or_none results in an execution of the underlying query.

.. seealso::

:meth:`_query.Query.first`

:meth:`_query.Query.one`

:meth:`_engine.Result.one_or_none` - v2 comparable method.

:meth:`_engine.Result.scalar_one_or_none` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def one_or_none(self) -> Optional[_T]:
    """Return at most one result or raise an exception.

    Returns ``None`` if the query selects
    no rows.  Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
    if multiple object identities are returned, or if multiple
    rows are returned for a query that returns only scalar values
    as opposed to full identity-mapped entities.

    Calling :meth:`_query.Query.one_or_none`
    results in an execution of the
    underlying query.

    .. seealso::

        :meth:`_query.Query.first`

        :meth:`_query.Query.one`

        :meth:`_engine.Result.one_or_none` - v2 comparable method.

        :meth:`_engine.Result.scalar_one_or_none` - v2 comparable method.

    """
    return self._iter().one_or_none()  # type: ignore

one

one() -> _T

Return exactly one result or raise an exception.

Raises sqlalchemy.orm.exc.NoResultFound if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

Calling :meth:.one results in an execution of the underlying query.

.. seealso::

:meth:`_query.Query.first`

:meth:`_query.Query.one_or_none`

:meth:`_engine.Result.one` - v2 comparable method.

:meth:`_engine.Result.scalar_one` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def one(self) -> _T:
    """Return exactly one result or raise an exception.

    Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
    no rows.  Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
    if multiple object identities are returned, or if multiple
    rows are returned for a query that returns only scalar values
    as opposed to full identity-mapped entities.

    Calling :meth:`.one` results in an execution of the underlying query.

    .. seealso::

        :meth:`_query.Query.first`

        :meth:`_query.Query.one_or_none`

        :meth:`_engine.Result.one` - v2 comparable method.

        :meth:`_engine.Result.scalar_one` - v2 comparable method.

    """
    return self._iter().one()  # type: ignore

scalar

scalar() -> Any

Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.

session.query(Item).scalar() session.query(Item.id).scalar() 1 session.query(Item.id).filter(Item.id < 0).scalar() None session.query(Item.id, Item.name).scalar() 1 session.query(func.count(Parent.id)).scalar() 20

This results in an execution of the underlying query.

.. seealso::

:meth:`_engine.Result.scalar` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def scalar(self) -> Any:
    """Return the first element of the first result or None
    if no rows present.  If multiple rows are returned,
    raises MultipleResultsFound.

      >>> session.query(Item).scalar()
      <Item>
      >>> session.query(Item.id).scalar()
      1
      >>> session.query(Item.id).filter(Item.id < 0).scalar()
      None
      >>> session.query(Item.id, Item.name).scalar()
      1
      >>> session.query(func.count(Parent.id)).scalar()
      20

    This results in an execution of the underlying query.

    .. seealso::

        :meth:`_engine.Result.scalar` - v2 comparable method.

    """
    # TODO: not sure why we can't use result.scalar() here
    try:
        ret = self.one()
        if not isinstance(ret, collections_abc.Sequence):
            return ret
        return ret[0]
    except sa_exc.NoResultFound:
        return None

instances

instances(
    result_proxy: CursorResult[Any],
    context: Optional[QueryContext] = None,
) -> Any

Return an ORM result given a :class:_engine.CursorResult and :class:.QueryContext.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.deprecated(
    "2.0",
    "The :meth:`_orm.Query.instances` method is deprecated and will "
    "be removed in a future release. "
    "Use the Select.from_statement() method or aliased() construct in "
    "conjunction with Session.execute() instead.",
)
def instances(
    self,
    result_proxy: CursorResult[Any],
    context: Optional[QueryContext] = None,
) -> Any:
    """Return an ORM result given a :class:`_engine.CursorResult` and
    :class:`.QueryContext`.

    """
    if context is None:
        util.warn_deprecated(
            "Using the Query.instances() method without a context "
            "is deprecated and will be disallowed in a future release.  "
            "Please make use of :meth:`_query.Query.from_statement` "
            "for linking ORM results to arbitrary select constructs.",
            version="1.4",
        )
        compile_state = self._compile_state(for_statement=False)

        context = QueryContext(
            compile_state,
            compile_state.statement,
            self._params,
            self.session,
            self.load_options,
        )

    result = loading.instances(result_proxy, context)

    # legacy: automatically set scalars, unique
    if result._attributes.get("is_single_entity", False):
        result = result.scalars()  # type: ignore

    if result._attributes.get("filtered", False):
        result = result.unique()

    # TODO: isn't this supposed to be a list?
    return result

merge_result

merge_result(
    iterator: Union[
        FrozenResult[Any],
        Iterable[Sequence[Any]],
        Iterable[object],
    ],
    load: bool = True,
) -> Union[FrozenResult[Any], Iterable[Any]]

Merge a result into this :class:_query.Query object's Session.

Given an iterator returned by a :class:_query.Query of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using :meth:.Session.merge. This is an optimized method which will merge all mapped instances, preserving the structure of the result rows and unmapped columns with less method overhead than that of calling :meth:.Session.merge explicitly for each value.

The structure of the results is determined based on the column list of this :class:_query.Query - if these do not correspond, unchecked errors will occur.

The 'load' argument is the same as that of :meth:.Session.merge.

For an example of how :meth:_query.Query.merge_result is used, see the source code for the example :ref:examples_caching, where :meth:_query.Query.merge_result is used to efficiently restore state from a cache back into a target :class:.Session.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
@util.became_legacy_20(
    ":meth:`_orm.Query.merge_result`",
    alternative="The method is superseded by the "
    ":func:`_orm.merge_frozen_result` function.",
    enable_warnings=False,  # warnings occur via loading.merge_result
)
def merge_result(
    self,
    iterator: Union[
        FrozenResult[Any], Iterable[Sequence[Any]], Iterable[object]
    ],
    load: bool = True,
) -> Union[FrozenResult[Any], Iterable[Any]]:
    """Merge a result into this :class:`_query.Query` object's Session.

    Given an iterator returned by a :class:`_query.Query`
    of the same structure
    as this one, return an identical iterator of results, with all mapped
    instances merged into the session using :meth:`.Session.merge`. This
    is an optimized method which will merge all mapped instances,
    preserving the structure of the result rows and unmapped columns with
    less method overhead than that of calling :meth:`.Session.merge`
    explicitly for each value.

    The structure of the results is determined based on the column list of
    this :class:`_query.Query` - if these do not correspond,
    unchecked errors
    will occur.

    The 'load' argument is the same as that of :meth:`.Session.merge`.

    For an example of how :meth:`_query.Query.merge_result` is used, see
    the source code for the example :ref:`examples_caching`, where
    :meth:`_query.Query.merge_result` is used to efficiently restore state
    from a cache back into a target :class:`.Session`.

    """

    return loading.merge_result(self, iterator, load)

exists

exists() -> Exists

A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...).

e.g.::

q = session.query(User).filter(User.name == 'fred')
session.query(q.exists())

Producing SQL similar to::

SELECT EXISTS (
    SELECT 1 FROM users WHERE users.name = :name_1
) AS anon_1

The EXISTS construct is usually used in the WHERE clause::

session.query(User.id).filter(q.exists()).scalar()

Note that some databases such as SQL Server don't allow an EXISTS expression to be present in the columns clause of a SELECT. To select a simple boolean value based on the exists as a WHERE, use :func:.literal::

from sqlalchemy import literal

session.query(literal(True)).filter(q.exists()).scalar()

.. seealso::

:meth:`_sql.Select.exists` - v2 comparable method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def exists(self) -> Exists:
    """A convenience method that turns a query into an EXISTS subquery
    of the form EXISTS (SELECT 1 FROM ... WHERE ...).

    e.g.::

        q = session.query(User).filter(User.name == 'fred')
        session.query(q.exists())

    Producing SQL similar to::

        SELECT EXISTS (
            SELECT 1 FROM users WHERE users.name = :name_1
        ) AS anon_1

    The EXISTS construct is usually used in the WHERE clause::

        session.query(User.id).filter(q.exists()).scalar()

    Note that some databases such as SQL Server don't allow an
    EXISTS expression to be present in the columns clause of a
    SELECT.    To select a simple boolean value based on the exists
    as a WHERE, use :func:`.literal`::

        from sqlalchemy import literal

        session.query(literal(True)).filter(q.exists()).scalar()

    .. seealso::

        :meth:`_sql.Select.exists` - v2 comparable method.

    """

    # .add_columns() for the case that we are a query().select_from(X),
    # so that ".statement" can be produced (#2995) but also without
    # omitting the FROM clause from a query(X) (#2818);
    # .with_only_columns() after we have a core select() so that
    # we get just "SELECT 1" without any entities.

    inner = (
        self.enable_eagerloads(False)
        .add_columns(sql.literal_column("1"))
        .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
        ._get_select_statement_only()
        .with_only_columns(1)
    )

    ezero = self._entity_from_pre_ent_zero()
    if ezero is not None:
        inner = inner.select_from(ezero)

    return sql.exists(inner)

count

count() -> int

Return a count of rows this the SQL formed by this :class:Query would return.

This generates the SQL for this Query as follows::

SELECT count(1) AS count_1 FROM (
    SELECT <rest of query follows...>
) AS anon_1

The above SQL returns a single row, which is the aggregate value of the count function; the :meth:_query.Query.count method then returns that single integer value.

.. warning::

It is important to note that the value returned by
count() is **not the same as the number of ORM objects that this
Query would return from a method such as the .all() method**.
The :class:`_query.Query` object,
when asked to return full entities,
will **deduplicate entries based on primary key**, meaning if the
same primary key value would appear in the results more than once,
only one object of that primary key would be present.  This does
not apply to a query that is against individual columns.

.. seealso::

    :ref:`faq_query_deduplicating`

For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use :attr:~sqlalchemy.sql.expression.func expressions in conjunction with :meth:~.Session.query, i.e.::

from sqlalchemy import func

# count User records, without
# using a subquery.
session.query(func.count(User.id))

# return count of user "id" grouped
# by "name"
session.query(func.count(User.id)).\
        group_by(User.name)

from sqlalchemy import distinct

# count distinct "name" values
session.query(func.count(distinct(User.name)))

.. seealso::

:ref:`migration_20_query_usage`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def count(self) -> int:
    r"""Return a count of rows this the SQL formed by this :class:`Query`
    would return.

    This generates the SQL for this Query as follows::

        SELECT count(1) AS count_1 FROM (
            SELECT <rest of query follows...>
        ) AS anon_1

    The above SQL returns a single row, which is the aggregate value
    of the count function; the :meth:`_query.Query.count`
    method then returns
    that single integer value.

    .. warning::

        It is important to note that the value returned by
        count() is **not the same as the number of ORM objects that this
        Query would return from a method such as the .all() method**.
        The :class:`_query.Query` object,
        when asked to return full entities,
        will **deduplicate entries based on primary key**, meaning if the
        same primary key value would appear in the results more than once,
        only one object of that primary key would be present.  This does
        not apply to a query that is against individual columns.

        .. seealso::

            :ref:`faq_query_deduplicating`

    For fine grained control over specific columns to count, to skip the
    usage of a subquery or otherwise control of the FROM clause, or to use
    other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func`
    expressions in conjunction with :meth:`~.Session.query`, i.e.::

        from sqlalchemy import func

        # count User records, without
        # using a subquery.
        session.query(func.count(User.id))

        # return count of user "id" grouped
        # by "name"
        session.query(func.count(User.id)).\
                group_by(User.name)

        from sqlalchemy import distinct

        # count distinct "name" values
        session.query(func.count(distinct(User.name)))

    .. seealso::

        :ref:`migration_20_query_usage`

    """
    col = sql.func.count(sql.literal_column("*"))
    return (  # type: ignore
        self._legacy_from_self(col).enable_eagerloads(False).scalar()
    )

delete

delete(
    synchronize_session: SynchronizeSessionArgument = "auto",
) -> int

Perform a DELETE with an arbitrary WHERE clause.

Deletes rows matched by this query from the database.

E.g.::

sess.query(User).filter(User.age == 25).\
    delete(synchronize_session=False)

sess.query(User).filter(User.age == 25).\
    delete(synchronize_session='evaluate')

.. warning::

See the section :ref:`orm_expression_update_delete` for important
caveats and warnings, including limitations when using bulk UPDATE
and DELETE with mapper inheritance configurations.

:param synchronize_session: chooses the strategy to update the attributes on objects in the session. See the section :ref:orm_expression_update_delete for a discussion of these strategies.

:return: the count of rows matched as returned by the database's "row count" feature.

.. seealso::

:ref:`orm_expression_update_delete`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def delete(
    self, synchronize_session: SynchronizeSessionArgument = "auto"
) -> int:
    r"""Perform a DELETE with an arbitrary WHERE clause.

    Deletes rows matched by this query from the database.

    E.g.::

        sess.query(User).filter(User.age == 25).\
            delete(synchronize_session=False)

        sess.query(User).filter(User.age == 25).\
            delete(synchronize_session='evaluate')

    .. warning::

        See the section :ref:`orm_expression_update_delete` for important
        caveats and warnings, including limitations when using bulk UPDATE
        and DELETE with mapper inheritance configurations.

    :param synchronize_session: chooses the strategy to update the
     attributes on objects in the session.   See the section
     :ref:`orm_expression_update_delete` for a discussion of these
     strategies.

    :return: the count of rows matched as returned by the database's
      "row count" feature.

    .. seealso::

        :ref:`orm_expression_update_delete`

    """

    bulk_del = BulkDelete(self)
    if self.dispatch.before_compile_delete:
        for fn in self.dispatch.before_compile_delete:
            new_query = fn(bulk_del.query, bulk_del)
            if new_query is not None:
                bulk_del.query = new_query

            self = bulk_del.query

    delete_ = sql.delete(*self._raw_columns)  # type: ignore
    delete_._where_criteria = self._where_criteria
    result: CursorResult[Any] = self.session.execute(
        delete_,
        self._params,
        execution_options=self._execution_options.union(
            {"synchronize_session": synchronize_session}
        ),
    )
    bulk_del.result = result  # type: ignore
    self.session.dispatch.after_bulk_delete(bulk_del)
    result.close()

    return result.rowcount

update

update(
    values: Dict[_DMLColumnArgument, Any],
    synchronize_session: SynchronizeSessionArgument = "auto",
    update_args: Optional[Dict[Any, Any]] = None,
) -> int

Perform an UPDATE with an arbitrary WHERE clause.

Updates rows matched by this query in the database.

E.g.::

sess.query(User).filter(User.age == 25).\
    update({User.age: User.age - 10}, synchronize_session=False)

sess.query(User).filter(User.age == 25).\
    update({"age": User.age - 10}, synchronize_session='evaluate')

.. warning::

See the section :ref:`orm_expression_update_delete` for important
caveats and warnings, including limitations when using arbitrary
UPDATE and DELETE with mapper inheritance configurations.

:param values: a dictionary with attributes names, or alternatively mapped attributes or SQL expressions, as keys, and literal values or sql expressions as values. If :ref:parameter-ordered mode <tutorial_parameter_ordered_updates> is desired, the values can be passed as a list of 2-tuples; this requires that the :paramref:~sqlalchemy.sql.expression.update.preserve_parameter_order flag is passed to the :paramref:.Query.update.update_args dictionary as well.

:param synchronize_session: chooses the strategy to update the attributes on objects in the session. See the section :ref:orm_expression_update_delete for a discussion of these strategies.

:param update_args: Optional dictionary, if present will be passed to the underlying :func:_expression.update construct as the **kw for the object. May be used to pass dialect-specific arguments such as mysql_limit, as well as other special arguments such as :paramref:~sqlalchemy.sql.expression.update.preserve_parameter_order.

:return: the count of rows matched as returned by the database's "row count" feature.

.. seealso::

:ref:`orm_expression_update_delete`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/query.py
def update(
    self,
    values: Dict[_DMLColumnArgument, Any],
    synchronize_session: SynchronizeSessionArgument = "auto",
    update_args: Optional[Dict[Any, Any]] = None,
) -> int:
    r"""Perform an UPDATE with an arbitrary WHERE clause.

    Updates rows matched by this query in the database.

    E.g.::

        sess.query(User).filter(User.age == 25).\
            update({User.age: User.age - 10}, synchronize_session=False)

        sess.query(User).filter(User.age == 25).\
            update({"age": User.age - 10}, synchronize_session='evaluate')

    .. warning::

        See the section :ref:`orm_expression_update_delete` for important
        caveats and warnings, including limitations when using arbitrary
        UPDATE and DELETE with mapper inheritance configurations.

    :param values: a dictionary with attributes names, or alternatively
     mapped attributes or SQL expressions, as keys, and literal
     values or sql expressions as values.   If :ref:`parameter-ordered
     mode <tutorial_parameter_ordered_updates>` is desired, the values can
     be passed as a list of 2-tuples; this requires that the
     :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
     flag is passed to the :paramref:`.Query.update.update_args` dictionary
     as well.

    :param synchronize_session: chooses the strategy to update the
     attributes on objects in the session.   See the section
     :ref:`orm_expression_update_delete` for a discussion of these
     strategies.

    :param update_args: Optional dictionary, if present will be passed
     to the underlying :func:`_expression.update`
     construct as the ``**kw`` for
     the object.  May be used to pass dialect-specific arguments such
     as ``mysql_limit``, as well as other special arguments such as
     :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.

    :return: the count of rows matched as returned by the database's
     "row count" feature.


    .. seealso::

        :ref:`orm_expression_update_delete`

    """

    update_args = update_args or {}

    bulk_ud = BulkUpdate(self, values, update_args)

    if self.dispatch.before_compile_update:
        for fn in self.dispatch.before_compile_update:
            new_query = fn(bulk_ud.query, bulk_ud)
            if new_query is not None:
                bulk_ud.query = new_query
        self = bulk_ud.query

    upd = sql.update(*self._raw_columns)  # type: ignore

    ppo = update_args.pop("preserve_parameter_order", False)
    if ppo:
        upd = upd.ordered_values(*values)  # type: ignore
    else:
        upd = upd.values(values)
    if update_args:
        upd = upd.with_dialect_options(**update_args)

    upd._where_criteria = self._where_criteria
    result: CursorResult[Any] = self.session.execute(
        upd,
        self._params,
        execution_options=self._execution_options.union(
            {"synchronize_session": synchronize_session}
        ),
    )
    bulk_ud.result = result  # type: ignore
    self.session.dispatch.after_bulk_update(bulk_ud)
    result.close()
    return result.rowcount

Registry

Registry(
    *,
    metadata: Optional[MetaData] = None,
    class_registry: Optional[_ClsRegistryType] = None,
    type_annotation_map: Optional[
        _TypeAnnotationMapType
    ] = None,
    constructor: Callable[
        ..., None
    ] = _declarative_constructor,
)

Generalized registry for mapping classes.

The :class:_orm.registry serves as the basis for maintaining a collection of mappings, and provides configurational hooks used to map classes.

The three general kinds of mappings supported are Declarative Base, Declarative Decorator, and Imperative Mapping. All of these mapping styles may be used interchangeably:

  • :meth:_orm.registry.generate_base returns a new declarative base class, and is the underlying implementation of the :func:_orm.declarative_base function.

  • :meth:_orm.registry.mapped provides a class decorator that will apply declarative mapping to a class without the use of a declarative base class.

  • :meth:_orm.registry.map_imperatively will produce a :class:_orm.Mapper for a class without scanning the class for declarative class attributes. This method suits the use case historically provided by the sqlalchemy.orm.mapper() classical mapping function, which is removed as of SQLAlchemy 2.0.

.. versionadded:: 1.4

.. seealso::

:ref:`orm_mapping_classes_toplevel` - overview of class mapping
styles.

Construct a new :class:_orm.registry

:param metadata: An optional :class:_schema.MetaData instance. All :class:_schema.Table objects generated using declarative table mapping will make use of this :class:_schema.MetaData collection. If this argument is left at its default of None, a blank :class:_schema.MetaData collection is created.

: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. The provided dict will update the default type mapping. 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`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def __init__(
    self,
    *,
    metadata: Optional[MetaData] = None,
    class_registry: Optional[clsregistry._ClsRegistryType] = None,
    type_annotation_map: Optional[_TypeAnnotationMapType] = None,
    constructor: Callable[..., None] = _declarative_constructor,
):
    r"""Construct a new :class:`_orm.registry`

    :param metadata:
      An optional :class:`_schema.MetaData` instance.  All
      :class:`_schema.Table` objects generated using declarative
      table mapping will make use of this :class:`_schema.MetaData`
      collection.  If this argument is left at its default of ``None``,
      a blank :class:`_schema.MetaData` collection is created.

    :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.
      The provided dict will update the default type mapping.  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`


    """
    lcl_metadata = metadata or MetaData()

    if class_registry is None:
        class_registry = weakref.WeakValueDictionary()

    self._class_registry = class_registry
    self._managers = weakref.WeakKeyDictionary()
    self._non_primary_mappers = weakref.WeakKeyDictionary()
    self.metadata = lcl_metadata
    self.constructor = constructor
    self.type_annotation_map = {}
    if type_annotation_map is not None:
        self.update_type_annotation_map(type_annotation_map)
    self._dependents = set()
    self._dependencies = set()

    self._new_mappers = False

    with mapperlib._CONFIGURE_MUTEX:
        mapperlib._mapper_registries[self] = True

mappers property

mappers: FrozenSet[Mapper[Any]]

read only collection of all :class:_orm.Mapper objects.

update_type_annotation_map

update_type_annotation_map(
    type_annotation_map: _TypeAnnotationMapType,
) -> None

update the :paramref:_orm.registry.type_annotation_map with new values.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def update_type_annotation_map(
    self,
    type_annotation_map: _TypeAnnotationMapType,
) -> None:
    """update the :paramref:`_orm.registry.type_annotation_map` with new
    values."""

    self.type_annotation_map.update(
        {
            sub_type: sqltype
            for typ, sqltype in type_annotation_map.items()
            for sub_type in compat_typing.expand_unions(
                typ, include_union=True, discard_none=True
            )
        }
    )

configure

configure(cascade: bool = False) -> None

Configure all as-yet unconfigured mappers in this :class:_orm.registry.

The configure step is used to reconcile and initialize the :func:_orm.relationship linkages between mapped classes, as well as to invoke configuration events such as the :meth:_orm.MapperEvents.before_configured and :meth:_orm.MapperEvents.after_configured, which may be used by ORM extensions or user-defined extension hooks.

If one or more mappers in this registry contain :func:_orm.relationship constructs that refer to mapped classes in other registries, this registry is said to be dependent on those registries. In order to configure those dependent registries automatically, the :paramref:_orm.registry.configure.cascade flag should be set to True. Otherwise, if they are not configured, an exception will be raised. The rationale behind this behavior is to allow an application to programmatically invoke configuration of registries while controlling whether or not the process implicitly reaches other registries.

As an alternative to invoking :meth:_orm.registry.configure, the ORM function :func:_orm.configure_mappers function may be used to ensure configuration is complete for all :class:_orm.registry objects in memory. This is generally simpler to use and also predates the usage of :class:_orm.registry objects overall. However, this function will impact all mappings throughout the running Python process and may be more memory/time consuming for an application that has many registries in use for different purposes that may not be needed immediately.

.. seealso::

:func:`_orm.configure_mappers`

.. versionadded:: 1.4.0b2

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def configure(self, cascade: bool = False) -> None:
    """Configure all as-yet unconfigured mappers in this
    :class:`_orm.registry`.

    The configure step is used to reconcile and initialize the
    :func:`_orm.relationship` linkages between mapped classes, as well as
    to invoke configuration events such as the
    :meth:`_orm.MapperEvents.before_configured` and
    :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM
    extensions or user-defined extension hooks.

    If one or more mappers in this registry contain
    :func:`_orm.relationship` constructs that refer to mapped classes in
    other registries, this registry is said to be *dependent* on those
    registries. In order to configure those dependent registries
    automatically, the :paramref:`_orm.registry.configure.cascade` flag
    should be set to ``True``. Otherwise, if they are not configured, an
    exception will be raised.  The rationale behind this behavior is to
    allow an application to programmatically invoke configuration of
    registries while controlling whether or not the process implicitly
    reaches other registries.

    As an alternative to invoking :meth:`_orm.registry.configure`, the ORM
    function :func:`_orm.configure_mappers` function may be used to ensure
    configuration is complete for all :class:`_orm.registry` objects in
    memory. This is generally simpler to use and also predates the usage of
    :class:`_orm.registry` objects overall. However, this function will
    impact all mappings throughout the running Python process and may be
    more memory/time consuming for an application that has many registries
    in use for different purposes that may not be needed immediately.

    .. seealso::

        :func:`_orm.configure_mappers`


    .. versionadded:: 1.4.0b2

    """
    mapperlib._configure_registries({self}, cascade=cascade)

dispose

dispose(cascade: bool = False) -> None

Dispose of all mappers in this :class:_orm.registry.

After invocation, all the classes that were mapped within this registry will no longer have class instrumentation associated with them. This method is the per-:class:_orm.registry analogue to the application-wide :func:_orm.clear_mappers function.

If this registry contains mappers that are dependencies of other registries, typically via :func:_orm.relationship links, then those registries must be disposed as well. When such registries exist in relation to this one, their :meth:_orm.registry.dispose method will also be called, if the :paramref:_orm.registry.dispose.cascade flag is set to True; otherwise, an error is raised if those registries were not already disposed.

.. versionadded:: 1.4.0b2

.. seealso::

:func:`_orm.clear_mappers`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def dispose(self, cascade: bool = False) -> None:
    """Dispose of all mappers in this :class:`_orm.registry`.

    After invocation, all the classes that were mapped within this registry
    will no longer have class instrumentation associated with them. This
    method is the per-:class:`_orm.registry` analogue to the
    application-wide :func:`_orm.clear_mappers` function.

    If this registry contains mappers that are dependencies of other
    registries, typically via :func:`_orm.relationship` links, then those
    registries must be disposed as well. When such registries exist in
    relation to this one, their :meth:`_orm.registry.dispose` method will
    also be called, if the :paramref:`_orm.registry.dispose.cascade` flag
    is set to ``True``; otherwise, an error is raised if those registries
    were not already disposed.

    .. versionadded:: 1.4.0b2

    .. seealso::

        :func:`_orm.clear_mappers`

    """

    mapperlib._dispose_registries({self}, cascade=cascade)

generate_base

generate_base(
    mapper: Optional[Callable[..., Mapper[Any]]] = None,
    cls: Type[Any] = object,
    name: str = "Base",
    metaclass: Type[Any] = DeclarativeMeta,
) -> Any

Generate a declarative base class.

Classes that inherit from the returned class object will be automatically mapped using declarative mapping.

E.g.::

from sqlalchemy.orm import registry

mapper_registry = registry()

Base = mapper_registry.generate_base()

class MyClass(Base):
    __tablename__ = "my_table"
    id = Column(Integer, primary_key=True)

The above dynamically generated class is equivalent to the non-dynamic example below::

from sqlalchemy.orm import registry
from sqlalchemy.orm.decl_api import DeclarativeMeta

mapper_registry = registry()

class Base(metaclass=DeclarativeMeta):
    __abstract__ = True
    registry = mapper_registry
    metadata = mapper_registry.metadata

    __init__ = mapper_registry.constructor

.. versionchanged:: 2.0 Note that the :meth:_orm.registry.generate_base method 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 :meth:_orm.registry.generate_base method provides the implementation for the :func:_orm.declarative_base function, which creates the :class:_orm.registry and base class all at once.

See the section :ref:orm_declarative_mapping for background and examples.

:param mapper: An optional callable, defaults to :class:_orm.Mapper. This function is used to generate new :class:_orm.Mapper objects.

: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 metaclass: Defaults to :class:.DeclarativeMeta. A metaclass or metaclass compatible callable to use as the meta type of the generated declarative base class.

.. seealso::

:ref:`orm_declarative_mapping`

:func:`_orm.declarative_base`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def generate_base(
    self,
    mapper: Optional[Callable[..., Mapper[Any]]] = None,
    cls: Type[Any] = object,
    name: str = "Base",
    metaclass: Type[Any] = DeclarativeMeta,
) -> Any:
    """Generate a declarative base class.

    Classes that inherit from the returned class object will be
    automatically mapped using declarative mapping.

    E.g.::

        from sqlalchemy.orm import registry

        mapper_registry = registry()

        Base = mapper_registry.generate_base()

        class MyClass(Base):
            __tablename__ = "my_table"
            id = Column(Integer, primary_key=True)

    The above dynamically generated class is equivalent to the
    non-dynamic example below::

        from sqlalchemy.orm import registry
        from sqlalchemy.orm.decl_api import DeclarativeMeta

        mapper_registry = registry()

        class Base(metaclass=DeclarativeMeta):
            __abstract__ = True
            registry = mapper_registry
            metadata = mapper_registry.metadata

            __init__ = mapper_registry.constructor

    .. versionchanged:: 2.0 Note that the
       :meth:`_orm.registry.generate_base` method 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 :meth:`_orm.registry.generate_base` method provides the
    implementation for the :func:`_orm.declarative_base` function, which
    creates the :class:`_orm.registry` and base class all at once.

    See the section :ref:`orm_declarative_mapping` for background and
    examples.

    :param mapper:
      An optional callable, defaults to :class:`_orm.Mapper`.
      This function is used to generate new :class:`_orm.Mapper` objects.

    :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 metaclass:
      Defaults to :class:`.DeclarativeMeta`.  A metaclass or __metaclass__
      compatible callable to use as the meta type of the generated
      declarative base class.

    .. seealso::

        :ref:`orm_declarative_mapping`

        :func:`_orm.declarative_base`

    """
    metadata = self.metadata

    bases = not isinstance(cls, tuple) and (cls,) or cls

    class_dict: Dict[str, Any] = dict(registry=self, metadata=metadata)
    if isinstance(cls, type):
        class_dict["__doc__"] = cls.__doc__

    if self.constructor is not None:
        class_dict["__init__"] = self.constructor

    class_dict["__abstract__"] = True
    if mapper:
        class_dict["__mapper_cls__"] = mapper

    if hasattr(cls, "__class_getitem__"):

        def __class_getitem__(cls: Type[_T], key: Any) -> Type[_T]:
            # allow generic classes in py3.9+
            return cls

        class_dict["__class_getitem__"] = __class_getitem__

    return metaclass(name, bases, class_dict)

mapped_as_dataclass

mapped_as_dataclass(__cls: Type[_O]) -> Type[_O]
mapped_as_dataclass(
    __cls: Literal[None] = ...,
    *,
    init: Union[_NoArg, bool] = ...,
    repr: Union[_NoArg, bool] = ...,
    eq: Union[_NoArg, bool] = ...,
    order: Union[_NoArg, bool] = ...,
    unsafe_hash: Union[_NoArg, bool] = ...,
    match_args: Union[_NoArg, bool] = ...,
    kw_only: Union[_NoArg, bool] = ...,
    dataclass_callable: Union[
        _NoArg, Callable[..., Type[Any]]
    ] = ...,
) -> Callable[[Type[_O]], Type[_O]]
mapped_as_dataclass(
    __cls: Optional[Type[_O]] = None,
    *,
    init: Union[_NoArg, bool] = NO_ARG,
    repr: Union[_NoArg, bool] = NO_ARG,
    eq: Union[_NoArg, bool] = NO_ARG,
    order: Union[_NoArg, bool] = NO_ARG,
    unsafe_hash: Union[_NoArg, bool] = NO_ARG,
    match_args: Union[_NoArg, bool] = NO_ARG,
    kw_only: Union[_NoArg, bool] = NO_ARG,
    dataclass_callable: Union[
        _NoArg, Callable[..., Type[Any]]
    ] = NO_ARG,
) -> Union[Type[_O], Callable[[Type[_O]], Type[_O]]]

Class decorator that will apply the Declarative mapping process to a given class, and additionally convert the class to be a Python dataclass.

.. seealso::

:ref:`orm_declarative_native_dataclasses` - complete background
on SQLAlchemy native dataclass mapping

.. versionadded:: 2.0

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def mapped_as_dataclass(
    self,
    __cls: Optional[Type[_O]] = None,
    *,
    init: Union[_NoArg, bool] = _NoArg.NO_ARG,
    repr: Union[_NoArg, bool] = _NoArg.NO_ARG,  # noqa: A002
    eq: Union[_NoArg, bool] = _NoArg.NO_ARG,
    order: Union[_NoArg, bool] = _NoArg.NO_ARG,
    unsafe_hash: Union[_NoArg, bool] = _NoArg.NO_ARG,
    match_args: Union[_NoArg, bool] = _NoArg.NO_ARG,
    kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
    dataclass_callable: Union[
        _NoArg, Callable[..., Type[Any]]
    ] = _NoArg.NO_ARG,
) -> Union[Type[_O], Callable[[Type[_O]], Type[_O]]]:
    """Class decorator that will apply the Declarative mapping process
    to a given class, and additionally convert the class to be a
    Python dataclass.

    .. seealso::

        :ref:`orm_declarative_native_dataclasses` - complete background
        on SQLAlchemy native dataclass mapping


    .. versionadded:: 2.0


    """

    def decorate(cls: Type[_O]) -> Type[_O]:
        setattr(
            cls,
            "_sa_apply_dc_transforms",
            {
                "init": init,
                "repr": repr,
                "eq": eq,
                "order": order,
                "unsafe_hash": unsafe_hash,
                "match_args": match_args,
                "kw_only": kw_only,
                "dataclass_callable": dataclass_callable,
            },
        )
        _as_declarative(self, cls, cls.__dict__)
        return cls

    if __cls:
        return decorate(__cls)
    else:
        return decorate

mapped

mapped(cls: Type[_O]) -> Type[_O]

Class decorator that will apply the Declarative mapping process to a given class.

E.g.::

from sqlalchemy.orm import registry

mapper_registry = registry()

@mapper_registry.mapped
class Foo:
    __tablename__ = 'some_table'

    id = Column(Integer, primary_key=True)
    name = Column(String)

See the section :ref:orm_declarative_mapping for complete details and examples.

:param cls: class to be mapped.

:return: the class that was passed.

.. seealso::

:ref:`orm_declarative_mapping`

:meth:`_orm.registry.generate_base` - generates a base class
that will apply Declarative mapping to subclasses automatically
using a Python metaclass.

.. seealso::

:meth:`_orm.registry.mapped_as_dataclass`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def mapped(self, cls: Type[_O]) -> Type[_O]:
    """Class decorator that will apply the Declarative mapping process
    to a given class.

    E.g.::

        from sqlalchemy.orm import registry

        mapper_registry = registry()

        @mapper_registry.mapped
        class Foo:
            __tablename__ = 'some_table'

            id = Column(Integer, primary_key=True)
            name = Column(String)

    See the section :ref:`orm_declarative_mapping` for complete
    details and examples.

    :param cls: class to be mapped.

    :return: the class that was passed.

    .. seealso::

        :ref:`orm_declarative_mapping`

        :meth:`_orm.registry.generate_base` - generates a base class
        that will apply Declarative mapping to subclasses automatically
        using a Python metaclass.

    .. seealso::

        :meth:`_orm.registry.mapped_as_dataclass`

    """
    _as_declarative(self, cls, cls.__dict__)
    return cls

as_declarative_base

as_declarative_base(
    **kw: Any,
) -> Callable[[Type[_T]], Type[_T]]

Class decorator which will invoke :meth:_orm.registry.generate_base for a given base class.

E.g.::

from sqlalchemy.orm import registry

mapper_registry = registry()

@mapper_registry.as_declarative_base()
class Base:
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()
    id = Column(Integer, primary_key=True)

class MyMappedClass(Base):
    # ...

All keyword arguments passed to :meth:_orm.registry.as_declarative_base are passed along to :meth:_orm.registry.generate_base.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def as_declarative_base(self, **kw: Any) -> Callable[[Type[_T]], Type[_T]]:
    """
    Class decorator which will invoke
    :meth:`_orm.registry.generate_base`
    for a given base class.

    E.g.::

        from sqlalchemy.orm import registry

        mapper_registry = registry()

        @mapper_registry.as_declarative_base()
        class Base:
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to
    :meth:`_orm.registry.as_declarative_base` are passed
    along to :meth:`_orm.registry.generate_base`.

    """

    def decorate(cls: Type[_T]) -> Type[_T]:
        kw["cls"] = cls
        kw["name"] = cls.__name__
        return self.generate_base(**kw)  # type: ignore

    return decorate

map_declaratively

map_declaratively(cls: Type[_O]) -> Mapper[_O]

Map a class declaratively.

In this form of mapping, the class is scanned for mapping information, including for columns to be associated with a table, and/or an actual table object.

Returns the :class:_orm.Mapper object.

E.g.::

from sqlalchemy.orm import registry

mapper_registry = registry()

class Foo:
    __tablename__ = 'some_table'

    id = Column(Integer, primary_key=True)
    name = Column(String)

mapper = mapper_registry.map_declaratively(Foo)

This function is more conveniently invoked indirectly via either the :meth:_orm.registry.mapped class decorator or by subclassing a declarative metaclass generated from :meth:_orm.registry.generate_base.

See the section :ref:orm_declarative_mapping for complete details and examples.

:param cls: class to be mapped.

:return: a :class:_orm.Mapper object.

.. seealso::

:ref:`orm_declarative_mapping`

:meth:`_orm.registry.mapped` - more common decorator interface
to this function.

:meth:`_orm.registry.map_imperatively`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def map_declaratively(self, cls: Type[_O]) -> Mapper[_O]:
    """Map a class declaratively.

    In this form of mapping, the class is scanned for mapping information,
    including for columns to be associated with a table, and/or an
    actual table object.

    Returns the :class:`_orm.Mapper` object.

    E.g.::

        from sqlalchemy.orm import registry

        mapper_registry = registry()

        class Foo:
            __tablename__ = 'some_table'

            id = Column(Integer, primary_key=True)
            name = Column(String)

        mapper = mapper_registry.map_declaratively(Foo)

    This function is more conveniently invoked indirectly via either the
    :meth:`_orm.registry.mapped` class decorator or by subclassing a
    declarative metaclass generated from
    :meth:`_orm.registry.generate_base`.

    See the section :ref:`orm_declarative_mapping` for complete
    details and examples.

    :param cls: class to be mapped.

    :return: a :class:`_orm.Mapper` object.

    .. seealso::

        :ref:`orm_declarative_mapping`

        :meth:`_orm.registry.mapped` - more common decorator interface
        to this function.

        :meth:`_orm.registry.map_imperatively`

    """
    _as_declarative(self, cls, cls.__dict__)
    return cls.__mapper__  # type: ignore

map_imperatively

map_imperatively(
    class_: Type[_O],
    local_table: Optional[FromClause] = None,
    **kw: Any,
) -> Mapper[_O]

Map a class imperatively.

In this form of mapping, the class is not scanned for any mapping information. Instead, all mapping constructs are passed as arguments.

This method is intended to be fully equivalent to the now-removed SQLAlchemy mapper() function, except that it's in terms of a particular registry.

E.g.::

from sqlalchemy.orm import registry

mapper_registry = registry()

my_table = Table(
    "my_table",
    mapper_registry.metadata,
    Column('id', Integer, primary_key=True)
)

class MyClass:
    pass

mapper_registry.map_imperatively(MyClass, my_table)

See the section :ref:orm_imperative_mapping for complete background and usage examples.

:param class_: The class to be mapped. Corresponds to the :paramref:_orm.Mapper.class_ parameter.

:param local_table: the :class:_schema.Table or other :class:_sql.FromClause object that is the subject of the mapping. Corresponds to the :paramref:_orm.Mapper.local_table parameter.

:param **kw: all other keyword arguments are passed to the :class:_orm.Mapper constructor directly.

.. seealso::

:ref:`orm_imperative_mapping`

:ref:`orm_declarative_mapping`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/decl_api.py
def map_imperatively(
    self,
    class_: Type[_O],
    local_table: Optional[FromClause] = None,
    **kw: Any,
) -> Mapper[_O]:
    r"""Map a class imperatively.

    In this form of mapping, the class is not scanned for any mapping
    information.  Instead, all mapping constructs are passed as
    arguments.

    This method is intended to be fully equivalent to the now-removed
    SQLAlchemy ``mapper()`` function, except that it's in terms of
    a particular registry.

    E.g.::

        from sqlalchemy.orm import registry

        mapper_registry = registry()

        my_table = Table(
            "my_table",
            mapper_registry.metadata,
            Column('id', Integer, primary_key=True)
        )

        class MyClass:
            pass

        mapper_registry.map_imperatively(MyClass, my_table)

    See the section :ref:`orm_imperative_mapping` for complete background
    and usage examples.

    :param class\_: The class to be mapped.  Corresponds to the
     :paramref:`_orm.Mapper.class_` parameter.

    :param local_table: the :class:`_schema.Table` or other
     :class:`_sql.FromClause` object that is the subject of the mapping.
     Corresponds to the
     :paramref:`_orm.Mapper.local_table` parameter.

    :param \**kw: all other keyword arguments are passed to the
     :class:`_orm.Mapper` constructor directly.

    .. seealso::

        :ref:`orm_imperative_mapping`

        :ref:`orm_declarative_mapping`

    """
    return _mapper(self, class_, local_table, kw)

RelationshipProperty

RelationshipProperty(
    argument: Optional[
        _RelationshipArgumentType[_T]
    ] = None,
    secondary: Optional[
        _RelationshipSecondaryArgument
    ] = None,
    *,
    uselist: Optional[bool] = None,
    collection_class: Optional[
        Union[
            Type[Collection[Any]],
            Callable[[], Collection[Any]],
        ]
    ] = None,
    primaryjoin: Optional[
        _RelationshipJoinConditionArgument
    ] = None,
    secondaryjoin: Optional[
        _RelationshipJoinConditionArgument
    ] = None,
    back_populates: Optional[str] = None,
    order_by: _ORMOrderByArgument = False,
    backref: Optional[ORMBackrefArgument] = None,
    overlaps: Optional[str] = None,
    post_update: bool = False,
    cascade: str = "save-update, merge",
    viewonly: bool = False,
    attribute_options: Optional[_AttributeOptions] = None,
    lazy: _LazyLoadArgumentType = "select",
    passive_deletes: Union[Literal["all"], bool] = False,
    passive_updates: bool = True,
    active_history: bool = False,
    enable_typechecks: bool = True,
    foreign_keys: Optional[
        _ORMColCollectionArgument
    ] = None,
    remote_side: Optional[_ORMColCollectionArgument] = None,
    join_depth: Optional[int] = None,
    comparator_factory: Optional[
        Type[Comparator[Any]]
    ] = None,
    single_parent: bool = False,
    innerjoin: bool = False,
    distinct_target_key: Optional[bool] = None,
    load_on_pending: bool = False,
    query_class: Optional[Type[Query[Any]]] = None,
    info: Optional[_InfoType] = None,
    omit_join: Literal[None, False] = None,
    sync_backref: Optional[bool] = None,
    doc: Optional[str] = None,
    bake_queries: Literal[True] = True,
    cascade_backrefs: Literal[False] = False,
    _local_remote_pairs: Optional[_ColumnPairs] = None,
    _legacy_inactive_history_style: bool = False,
)

Bases: _IntrospectsAnnotations, StrategizedProperty[_T], Identified

Describes an object property that holds a single item or list of items that correspond to a related database table.

Public constructor is the :func:_orm.relationship function.

.. seealso::

:ref:`relationship_config_toplevel`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def __init__(
    self,
    argument: Optional[_RelationshipArgumentType[_T]] = None,
    secondary: Optional[_RelationshipSecondaryArgument] = None,
    *,
    uselist: Optional[bool] = None,
    collection_class: Optional[
        Union[Type[Collection[Any]], Callable[[], Collection[Any]]]
    ] = None,
    primaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    back_populates: Optional[str] = None,
    order_by: _ORMOrderByArgument = False,
    backref: Optional[ORMBackrefArgument] = None,
    overlaps: Optional[str] = None,
    post_update: bool = False,
    cascade: str = "save-update, merge",
    viewonly: bool = False,
    attribute_options: Optional[_AttributeOptions] = None,
    lazy: _LazyLoadArgumentType = "select",
    passive_deletes: Union[Literal["all"], bool] = False,
    passive_updates: bool = True,
    active_history: bool = False,
    enable_typechecks: bool = True,
    foreign_keys: Optional[_ORMColCollectionArgument] = None,
    remote_side: Optional[_ORMColCollectionArgument] = None,
    join_depth: Optional[int] = None,
    comparator_factory: Optional[
        Type[RelationshipProperty.Comparator[Any]]
    ] = None,
    single_parent: bool = False,
    innerjoin: bool = False,
    distinct_target_key: Optional[bool] = None,
    load_on_pending: bool = False,
    query_class: Optional[Type[Query[Any]]] = None,
    info: Optional[_InfoType] = None,
    omit_join: Literal[None, False] = None,
    sync_backref: Optional[bool] = None,
    doc: Optional[str] = None,
    bake_queries: Literal[True] = True,
    cascade_backrefs: Literal[False] = False,
    _local_remote_pairs: Optional[_ColumnPairs] = None,
    _legacy_inactive_history_style: bool = False,
):
    super().__init__(attribute_options=attribute_options)

    self.uselist = uselist
    self.argument = argument

    self._init_args = _RelationshipArgs(
        _RelationshipArg("secondary", secondary, None),
        _RelationshipArg("primaryjoin", primaryjoin, None),
        _RelationshipArg("secondaryjoin", secondaryjoin, None),
        _RelationshipArg("order_by", order_by, None),
        _RelationshipArg("foreign_keys", foreign_keys, None),
        _RelationshipArg("remote_side", remote_side, None),
    )

    self.post_update = post_update
    self.viewonly = viewonly
    if viewonly:
        self._warn_for_persistence_only_flags(
            passive_deletes=passive_deletes,
            passive_updates=passive_updates,
            enable_typechecks=enable_typechecks,
            active_history=active_history,
            cascade_backrefs=cascade_backrefs,
        )
    if viewonly and sync_backref:
        raise sa_exc.ArgumentError(
            "sync_backref and viewonly cannot both be True"
        )
    self.sync_backref = sync_backref
    self.lazy = lazy
    self.single_parent = single_parent
    self.collection_class = collection_class
    self.passive_deletes = passive_deletes

    if cascade_backrefs:
        raise sa_exc.ArgumentError(
            "The 'cascade_backrefs' parameter passed to "
            "relationship() may only be set to False."
        )

    self.passive_updates = passive_updates
    self.enable_typechecks = enable_typechecks
    self.query_class = query_class
    self.innerjoin = innerjoin
    self.distinct_target_key = distinct_target_key
    self.doc = doc
    self.active_history = active_history
    self._legacy_inactive_history_style = _legacy_inactive_history_style

    self.join_depth = join_depth
    if omit_join:
        util.warn(
            "setting omit_join to True is not supported; selectin "
            "loading of this relationship may not work correctly if this "
            "flag is set explicitly.  omit_join optimization is "
            "automatically detected for conditions under which it is "
            "supported."
        )

    self.omit_join = omit_join
    self.local_remote_pairs = _local_remote_pairs
    self.load_on_pending = load_on_pending
    self.comparator_factory = (
        comparator_factory or RelationshipProperty.Comparator
    )
    util.set_creation_order(self)

    if info is not None:
        self.info.update(info)

    self.strategy_key = (("lazy", self.lazy),)

    self._reverse_property: Set[RelationshipProperty[Any]] = set()

    if overlaps:
        self._overlaps = set(re.split(r"\s*,\s*", overlaps))  # type: ignore  # noqa: E501
    else:
        self._overlaps = ()

    # mypy ignoring the @property setter
    self.cascade = cascade  # type: ignore

    self.back_populates = back_populates

    if self.back_populates:
        if backref:
            raise sa_exc.ArgumentError(
                "backref and back_populates keyword arguments "
                "are mutually exclusive"
            )
        self.backref = None
    else:
        self.backref = backref

is_selectable class-attribute instance-attribute

is_selectable = False

Return True if this object is an instance of :class:_expression.Selectable.

is_aliased_class class-attribute instance-attribute

is_aliased_class = False

True if this object is an instance of :class:.AliasedClass.

is_instance class-attribute instance-attribute

is_instance = False

True if this object is an instance of :class:.InstanceState.

is_mapper class-attribute instance-attribute

is_mapper = False

True if this object is an instance of :class:_orm.Mapper.

is_bundle class-attribute instance-attribute

is_bundle = False

True if this object is an instance of :class:.Bundle.

is_property class-attribute instance-attribute

is_property = True

Part of the InspectionAttr interface; states this object is a mapper property.

is_attribute class-attribute instance-attribute

is_attribute = False

True if this object is a Python :term:descriptor.

This can refer to one of many types. Usually a :class:.QueryableAttribute which handles attributes events on behalf of a :class:.MapperProperty. But can also be an extension type such as :class:.AssociationProxy or :class:.hybrid_property. The :attr:.InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

.. seealso::

:attr:`_orm.Mapper.all_orm_descriptors`

is_clause_element class-attribute instance-attribute

is_clause_element = False

True if this object is an instance of :class:_expression.ClauseElement.

extension_type class-attribute instance-attribute

extension_type: InspectionAttrExtensionType = NOT_EXTENSION

The extension type, if any. Defaults to :attr:.interfaces.NotExtension.NOT_EXTENSION

.. seealso::

:class:`.HybridExtensionType`

:class:`.AssociationProxyExtensionType`

info instance-attribute

info: _InfoType

Info dictionary associated with the object, allowing user-defined data to be associated with this :class:.InspectionAttr.

The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:.column_property, :func:_orm.relationship, or :func:.composite functions.

.. seealso::

:attr:`.QueryableAttribute.info`

:attr:`.SchemaItem.info`

comparator instance-attribute

comparator: PropComparator[_T]

The :class:_orm.PropComparator instance that implements SQL expression construction on behalf of this mapped attribute.

key instance-attribute

key: str

name of class attribute

parent instance-attribute

parent: Mapper[Any]

the :class:.Mapper managing this property.

class_attribute property

class_attribute: InstrumentedAttribute[_T]

Return the class-bound descriptor corresponding to this :class:.MapperProperty.

This is basically a getattr() call::

return getattr(self.parent.class_, self.key)

I.e. if this :class:.MapperProperty were named addresses, and the class to which it is mapped is User, this sequence is possible::

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
>>> addresses_property = mapper.attrs.addresses
>>> addresses_property.class_attribute is User.addresses
True
>>> User.addresses.property is addresses_property
True

inherit_cache class-attribute instance-attribute

inherit_cache = True

:meta private:

cascade property writable

cascade: CascadeOptions

Return the current cascade setting for this :class:.RelationshipProperty.

Comparator

Comparator(
    prop: RelationshipProperty[_PT],
    parentmapper: _InternalEntityType[Any],
    adapt_to_entity: Optional[AliasedInsp[Any]] = None,
    of_type: Optional[_EntityType[_PT]] = None,
    extra_criteria: Tuple[ColumnElement[bool], ...] = (),
)

Bases: MemoizedSlots, PropComparator[_PT]

Produce boolean, comparison, and other operators for :class:.RelationshipProperty attributes.

See the documentation for :class:.PropComparator for a brief overview of ORM level operator definition.

.. seealso::

:class:`.PropComparator`

:class:`.ColumnProperty.Comparator`

:class:`.ColumnOperators`

:ref:`types_operators`

:attr:`.TypeEngine.comparator_factory`

Construction of :class:.RelationshipProperty.Comparator is internal to the ORM's attribute mechanics.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def __init__(
    self,
    prop: RelationshipProperty[_PT],
    parentmapper: _InternalEntityType[Any],
    adapt_to_entity: Optional[AliasedInsp[Any]] = None,
    of_type: Optional[_EntityType[_PT]] = None,
    extra_criteria: Tuple[ColumnElement[bool], ...] = (),
):
    """Construction of :class:`.RelationshipProperty.Comparator`
    is internal to the ORM's attribute mechanics.

    """
    self.prop = prop
    self._parententity = parentmapper
    self._adapt_to_entity = adapt_to_entity
    if of_type:
        self._of_type = of_type
    else:
        self._of_type = None
    self._extra_criteria = extra_criteria
timetuple class-attribute instance-attribute
timetuple: Literal[None] = None

Hack, allows datetime objects to be compared on the LHS.

entity instance-attribute
entity: _InternalEntityType[_PT]

The target entity referred to by this :class:.RelationshipProperty.Comparator.

This is either a :class:_orm.Mapper or :class:.AliasedInsp object.

This is the "target" or "remote" side of the :func:_orm.relationship.

mapper instance-attribute
mapper: Mapper[_PT]

The target :class:_orm.Mapper referred to by this :class:.RelationshipProperty.Comparator.

This is the "target" or "remote" side of the :func:_orm.relationship.

property
property() -> MapperProperty[_T_co]

Return the :class:.MapperProperty associated with this :class:.PropComparator.

Return values here will commonly be instances of :class:.ColumnProperty or :class:.Relationship.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.non_memoized_property
def property(self) -> MapperProperty[_T_co]:
    """Return the :class:`.MapperProperty` associated with this
    :class:`.PropComparator`.


    Return values here will commonly be instances of
    :class:`.ColumnProperty` or :class:`.Relationship`.


    """
    return self.prop
adapter
adapter() -> Optional[_ORMAdapterProto]

Produce a callable that adapts column expressions to suit an aliased version of this comparator.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
@util.ro_non_memoized_property
def adapter(self) -> Optional[_ORMAdapterProto]:
    """Produce a callable that adapts column expressions
    to suit an aliased version of this comparator.

    """
    if self._adapt_to_entity is None:
        return None
    else:
        return self._adapt_to_entity._orm_adapt_element
of_type
of_type(class_: _EntityType[Any]) -> PropComparator[_PT]

Redefine this object in terms of a polymorphic subclass.

See :meth:.PropComparator.of_type for an example.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def of_type(self, class_: _EntityType[Any]) -> PropComparator[_PT]:
    r"""Redefine this object in terms of a polymorphic subclass.

    See :meth:`.PropComparator.of_type` for an example.


    """
    return RelationshipProperty.Comparator(
        self.prop,
        self._parententity,
        adapt_to_entity=self._adapt_to_entity,
        of_type=class_,
        extra_criteria=self._extra_criteria,
    )
and_
and_(
    *criteria: _ColumnExpressionArgument[bool],
) -> PropComparator[Any]

Add AND criteria.

See :meth:.PropComparator.and_ for an example.

.. versionadded:: 1.4

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def and_(
    self, *criteria: _ColumnExpressionArgument[bool]
) -> PropComparator[Any]:
    """Add AND criteria.

    See :meth:`.PropComparator.and_` for an example.

    .. versionadded:: 1.4

    """
    exprs = tuple(
        coercions.expect(roles.WhereHavingRole, clause)
        for clause in util.coerce_generator_arg(criteria)
    )

    return RelationshipProperty.Comparator(
        self.prop,
        self._parententity,
        adapt_to_entity=self._adapt_to_entity,
        of_type=self._of_type,
        extra_criteria=self._extra_criteria + exprs,
    )
in_
in_(other: Any) -> NoReturn

Produce an IN clause - this is not implemented for :func:_orm.relationship-based attributes at this time.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def in_(self, other: Any) -> NoReturn:
    """Produce an IN clause - this is not implemented
    for :func:`_orm.relationship`-based attributes at this time.

    """
    raise NotImplementedError(
        "in_() not yet supported for "
        "relationships.  For a simple "
        "many-to-one, use in_() against "
        "the set of foreign key values."
    )
any
any(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Produce an expression that tests a collection against particular criterion, using EXISTS.

An expression like::

session.query(MyClass).filter(
    MyClass.somereference.any(SomeRelated.x==2)
)

Will produce a query like::

SELECT * FROM my_table WHERE
EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
AND related.x=2)

Because :meth:~.Relationship.Comparator.any uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.

:meth:~.Relationship.Comparator.any is particularly useful for testing for empty collections::

session.query(MyClass).filter(
    ~MyClass.somereference.any()
)

will produce::

SELECT * FROM my_table WHERE
NOT (EXISTS (SELECT 1 FROM related WHERE
related.my_id=my_table.id))

:meth:~.Relationship.Comparator.any is only valid for collections, i.e. a :func:_orm.relationship that has uselist=True. For scalar references, use :meth:~.Relationship.Comparator.has.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def any(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    """Produce an expression that tests a collection against
    particular criterion, using EXISTS.

    An expression like::

        session.query(MyClass).filter(
            MyClass.somereference.any(SomeRelated.x==2)
        )


    Will produce a query like::

        SELECT * FROM my_table WHERE
        EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
        AND related.x=2)

    Because :meth:`~.Relationship.Comparator.any` uses
    a correlated subquery, its performance is not nearly as
    good when compared against large target tables as that of
    using a join.

    :meth:`~.Relationship.Comparator.any` is particularly
    useful for testing for empty collections::

        session.query(MyClass).filter(
            ~MyClass.somereference.any()
        )

    will produce::

        SELECT * FROM my_table WHERE
        NOT (EXISTS (SELECT 1 FROM related WHERE
        related.my_id=my_table.id))

    :meth:`~.Relationship.Comparator.any` is only
    valid for collections, i.e. a :func:`_orm.relationship`
    that has ``uselist=True``.  For scalar references,
    use :meth:`~.Relationship.Comparator.has`.

    """
    if not self.property.uselist:
        raise sa_exc.InvalidRequestError(
            "'any()' not implemented for scalar "
            "attributes. Use has()."
        )

    return self._criterion_exists(criterion, **kwargs)
has
has(
    criterion: Optional[
        _ColumnExpressionArgument[bool]
    ] = None,
    **kwargs: Any,
) -> ColumnElement[bool]

Produce an expression that tests a scalar reference against particular criterion, using EXISTS.

An expression like::

session.query(MyClass).filter(
    MyClass.somereference.has(SomeRelated.x==2)
)

Will produce a query like::

SELECT * FROM my_table WHERE
EXISTS (SELECT 1 FROM related WHERE
related.id==my_table.related_id AND related.x=2)

Because :meth:~.Relationship.Comparator.has uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.

:meth:~.Relationship.Comparator.has is only valid for scalar references, i.e. a :func:_orm.relationship that has uselist=False. For collection references, use :meth:~.Relationship.Comparator.any.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def has(
    self,
    criterion: Optional[_ColumnExpressionArgument[bool]] = None,
    **kwargs: Any,
) -> ColumnElement[bool]:
    """Produce an expression that tests a scalar reference against
    particular criterion, using EXISTS.

    An expression like::

        session.query(MyClass).filter(
            MyClass.somereference.has(SomeRelated.x==2)
        )


    Will produce a query like::

        SELECT * FROM my_table WHERE
        EXISTS (SELECT 1 FROM related WHERE
        related.id==my_table.related_id AND related.x=2)

    Because :meth:`~.Relationship.Comparator.has` uses
    a correlated subquery, its performance is not nearly as
    good when compared against large target tables as that of
    using a join.

    :meth:`~.Relationship.Comparator.has` is only
    valid for scalar references, i.e. a :func:`_orm.relationship`
    that has ``uselist=False``.  For collection references,
    use :meth:`~.Relationship.Comparator.any`.

    """
    if self.property.uselist:
        raise sa_exc.InvalidRequestError(
            "'has()' not implemented for collections. Use any()."
        )
    return self._criterion_exists(criterion, **kwargs)
contains
contains(
    other: _ColumnExpressionArgument[Any], **kwargs: Any
) -> ColumnElement[bool]

Return a simple expression that tests a collection for containment of a particular item.

:meth:~.Relationship.Comparator.contains is only valid for a collection, i.e. a :func:_orm.relationship that implements one-to-many or many-to-many with uselist=True.

When used in a simple one-to-many context, an expression like::

MyClass.contains(other)

Produces a clause like::

mytable.id == <some id>

Where <some id> is the value of the foreign key attribute on other which refers to the primary key of its parent object. From this it follows that :meth:~.Relationship.Comparator.contains is very useful when used with simple one-to-many operations.

For many-to-many operations, the behavior of :meth:~.Relationship.Comparator.contains has more caveats. The association table will be rendered in the statement, producing an "implicit" join, that is, includes multiple tables in the FROM clause which are equated in the WHERE clause::

query(MyClass).filter(MyClass.contains(other))

Produces a query like::

SELECT * FROM my_table, my_association_table AS
my_association_table_1 WHERE
my_table.id = my_association_table_1.parent_id
AND my_association_table_1.child_id = <some id>

Where <some id> would be the primary key of other. From the above, it is clear that :meth:~.Relationship.Comparator.contains will not work with many-to-many collections when used in queries that move beyond simple AND conjunctions, such as multiple :meth:~.Relationship.Comparator.contains expressions joined by OR. In such cases subqueries or explicit "outer joins" will need to be used instead. See :meth:~.Relationship.Comparator.any for a less-performant alternative using EXISTS, or refer to :meth:_query.Query.outerjoin as well as :ref:orm_queryguide_joins for more details on constructing outer joins.

kwargs may be ignored by this operator but are required for API conformance.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
def contains(
    self, other: _ColumnExpressionArgument[Any], **kwargs: Any
) -> ColumnElement[bool]:
    """Return a simple expression that tests a collection for
    containment of a particular item.

    :meth:`~.Relationship.Comparator.contains` is
    only valid for a collection, i.e. a
    :func:`_orm.relationship` that implements
    one-to-many or many-to-many with ``uselist=True``.

    When used in a simple one-to-many context, an
    expression like::

        MyClass.contains(other)

    Produces a clause like::

        mytable.id == <some id>

    Where ``<some id>`` is the value of the foreign key
    attribute on ``other`` which refers to the primary
    key of its parent object. From this it follows that
    :meth:`~.Relationship.Comparator.contains` is
    very useful when used with simple one-to-many
    operations.

    For many-to-many operations, the behavior of
    :meth:`~.Relationship.Comparator.contains`
    has more caveats. The association table will be
    rendered in the statement, producing an "implicit"
    join, that is, includes multiple tables in the FROM
    clause which are equated in the WHERE clause::

        query(MyClass).filter(MyClass.contains(other))

    Produces a query like::

        SELECT * FROM my_table, my_association_table AS
        my_association_table_1 WHERE
        my_table.id = my_association_table_1.parent_id
        AND my_association_table_1.child_id = <some id>

    Where ``<some id>`` would be the primary key of
    ``other``. From the above, it is clear that
    :meth:`~.Relationship.Comparator.contains`
    will **not** work with many-to-many collections when
    used in queries that move beyond simple AND
    conjunctions, such as multiple
    :meth:`~.Relationship.Comparator.contains`
    expressions joined by OR. In such cases subqueries or
    explicit "outer joins" will need to be used instead.
    See :meth:`~.Relationship.Comparator.any` for
    a less-performant alternative using EXISTS, or refer
    to :meth:`_query.Query.outerjoin`
    as well as :ref:`orm_queryguide_joins`
    for more details on constructing outer joins.

    kwargs may be ignored by this operator but are required for API
    conformance.
    """
    if not self.prop.uselist:
        raise sa_exc.InvalidRequestError(
            "'contains' not implemented for scalar "
            "attributes.  Use =="
        )

    clause = self.prop._optimized_compare(
        other, adapt_source=self.adapter
    )

    if self.prop.secondaryjoin is not None:
        clause.negation_clause = self.__negated_contains_or_equals(
            other
        )

    return clause

set_parent

set_parent(parent: Mapper[Any], init: bool) -> None

Set the parent mapper that references this MapperProperty.

This method is overridden by some subclasses to perform extra setup when the mapper is first known.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def set_parent(self, parent: Mapper[Any], init: bool) -> None:
    """Set the parent mapper that references this MapperProperty.

    This method is overridden by some subclasses to perform extra
    setup when the mapper is first known.

    """
    self.parent = parent

init

init() -> None

Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def init(self) -> None:
    """Called after all mappers are created to assemble
    relationships between mappers and perform other post-mapper-creation
    initialization steps.


    """
    self._configure_started = True
    self.do_init()
    self._configure_finished = True

found_in_pep593_annotated

found_in_pep593_annotated() -> Any

return a copy of this object to use in declarative when the object is found inside of an Annotated object.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/interfaces.py
def found_in_pep593_annotated(self) -> Any:
    """return a copy of this object to use in declarative when the
    object is found inside of an Annotated object."""

    raise NotImplementedError(
        f"Use of the {self.__class__} construct inside of an "
        f"Annotated object is not yet supported."
    )

entity

entity() -> _InternalEntityType[_T]

Return the target mapped entity, which is an inspect() of the class or aliased class that is referenced by this :class:.RelationshipProperty.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
@util.memoized_property
def entity(self) -> _InternalEntityType[_T]:
    """Return the target mapped entity, which is an inspect() of the
    class or aliased class that is referenced by this
    :class:`.RelationshipProperty`.

    """
    self.parent._check_configure()
    return self.entity

mapper

mapper() -> Mapper[_T]

Return the targeted :class:_orm.Mapper for this :class:.RelationshipProperty.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.py
@util.memoized_property
def mapper(self) -> Mapper[_T]:
    """Return the targeted :class:`_orm.Mapper` for this
    :class:`.RelationshipProperty`.

    """
    return self.entity.mapper

Relationship

Relationship(
    argument: Optional[
        _RelationshipArgumentType[Any]
    ] = None,
    secondary: Optional[
        _RelationshipSecondaryArgument
    ] = None,
    *,
    uselist: Optional[bool] = None,
    collection_class: Optional[
        Union[
            Type[Collection[Any]],
            Callable[[], Collection[Any]],
        ]
    ] = None,
    primaryjoin: Optional[
        _RelationshipJoinConditionArgument
    ] = None,
    secondaryjoin: Optional[
        _RelationshipJoinConditionArgument
    ] = None,
    back_populates: Optional[str] = None,
    order_by: _ORMOrderByArgument = False,
    backref: Optional[ORMBackrefArgument] = None,
    overlaps: Optional[str] = None,
    post_update: bool = False,
    cascade: str = "save-update, merge",
    viewonly: bool = False,
    init: Union[_NoArg, bool] = NO_ARG,
    repr: Union[_NoArg, bool] = NO_ARG,
    default: Union[_NoArg, _T] = NO_ARG,
    default_factory: Union[
        _NoArg, Callable[[], _T]
    ] = NO_ARG,
    compare: Union[_NoArg, bool] = NO_ARG,
    kw_only: Union[_NoArg, bool] = NO_ARG,
    lazy: _LazyLoadArgumentType = "select",
    passive_deletes: Union[Literal["all"], bool] = False,
    passive_updates: bool = True,
    active_history: bool = False,
    enable_typechecks: bool = True,
    foreign_keys: Optional[
        _ORMColCollectionArgument
    ] = None,
    remote_side: Optional[_ORMColCollectionArgument] = None,
    join_depth: Optional[int] = None,
    comparator_factory: Optional[
        Type[Comparator[Any]]
    ] = None,
    single_parent: bool = False,
    innerjoin: bool = False,
    distinct_target_key: Optional[bool] = None,
    load_on_pending: bool = False,
    query_class: Optional[Type[Query[Any]]] = None,
    info: Optional[_InfoType] = None,
    omit_join: Literal[None, False] = None,
    sync_backref: Optional[bool] = None,
    **kw: Any,
) -> Relationship[Any]

Provide a relationship between two mapped classes.

This corresponds to a parent-child or associative table relationship. The constructed class is an instance of :class:.Relationship.

.. seealso::

:ref:`tutorial_orm_related_objects` - tutorial introduction
to :func:`_orm.relationship` in the :ref:`unified_tutorial`

:ref:`relationship_config_toplevel` - narrative documentation

:param argument: This parameter refers to the class that is to be related. It accepts several forms, including a direct reference to the target class itself, the :class:_orm.Mapper instance for the target class, a Python callable / lambda that will return a reference to the class or :class:_orm.Mapper when called, and finally a string name for the class, which will be resolved from the :class:_orm.registry in use in order to locate the class, e.g.::

    class SomeClass(Base):
        # ...

        related = relationship("RelatedClass")

The :paramref:_orm.relationship.argument may also be omitted from the :func:_orm.relationship construct entirely, and instead placed inside a :class:_orm.Mapped annotation on the left side, which should include a Python collection type if the relationship is expected to be a collection, such as::

    class SomeClass(Base):
        # ...

        related_items: Mapped[List["RelatedItem"]] = relationship()

Or for a many-to-one or one-to-one relationship::

    class SomeClass(Base):
        # ...

        related_item: Mapped["RelatedItem"] = relationship()

.. seealso::

:ref:`orm_declarative_properties` - further detail
on relationship configuration when using Declarative.

:param secondary: For a many-to-many relationship, specifies the intermediary table, and is typically an instance of :class:_schema.Table. In less common circumstances, the argument may also be specified as an :class:_expression.Alias construct, or even a :class:_expression.Join construct.

:paramref:_orm.relationship.secondary may also be passed as a callable function which is evaluated at mapper initialization time. When using Declarative, it may also be a string argument noting the name of a :class:_schema.Table that is present in the :class:_schema.MetaData collection associated with the parent-mapped :class:_schema.Table.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

The :paramref:_orm.relationship.secondary keyword argument is typically applied in the case where the intermediary :class:_schema.Table is not otherwise expressed in any direct class mapping. If the "secondary" table is also explicitly mapped elsewhere (e.g. as in :ref:association_pattern), one should consider applying the :paramref:_orm.relationship.viewonly flag so that this :func:_orm.relationship is not used for persistence operations which may conflict with those of the association object pattern.

.. seealso::

  :ref:`relationships_many_to_many` - Reference example of "many
  to many".

  :ref:`self_referential_many_to_many` - Specifics on using
  many-to-many in a self-referential case.

  :ref:`declarative_many_to_many` - Additional options when using
  Declarative.

  :ref:`association_pattern` - an alternative to
  :paramref:`_orm.relationship.secondary`
  when composing association
  table relationships, allowing additional attributes to be
  specified on the association table.

  :ref:`composite_secondary_join` - a lesser-used pattern which
  in some cases can enable complex :func:`_orm.relationship` SQL
  conditions to be used.

:param active_history=False: When True, indicates that the "previous" value for a many-to-one reference should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple many-to-ones only needs to be aware of the "new" value in order to perform a flush. This flag is available for applications that make use of :func:.attributes.get_history which also need to know the "previous" value of the attribute.

:param backref: A reference to a string relationship name, or a :func:_orm.backref construct, which will be used to automatically generate a new :func:_orm.relationship on the related class, which then refers to this one using a bi-directional :paramref:_orm.relationship.back_populates configuration.

In modern Python, explicit use of :func:_orm.relationship with :paramref:_orm.relationship.back_populates should be preferred, as it is more robust in terms of mapper configuration as well as more conceptually straightforward. It also integrates with new :pep:484 typing features introduced in SQLAlchemy 2.0 which is not possible with dynamically generated attributes.

.. seealso::

:ref:`relationships_backref` - notes on using
:paramref:`_orm.relationship.backref`

:ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
presents an overview of bi-directional relationship configuration
and behaviors using :paramref:`_orm.relationship.back_populates`

:func:`.backref` - allows control over :func:`_orm.relationship`
configuration when using :paramref:`_orm.relationship.backref`.

:param back_populates: Indicates the name of a :func:_orm.relationship on the related class that will be synchronized with this one. It is usually expected that the :func:_orm.relationship on the related class also refer to this one. This allows objects on both sides of each :func:_orm.relationship to synchronize in-Python state changes and also provides directives to the :term:unit of work flush process how changes along these relationships should be persisted.

.. seealso::

:ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
presents an overview of bi-directional relationship configuration
and behaviors.

:ref:`relationship_patterns` - includes many examples of
:paramref:`_orm.relationship.back_populates`.

:paramref:`_orm.relationship.backref` - legacy form which allows
more succinct configuration, but does not support explicit typing

:param overlaps: A string name or comma-delimited set of names of other relationships on either this mapper, a descendant mapper, or a target mapper with which this relationship may write to the same foreign keys upon persistence. The only effect this has is to eliminate the warning that this relationship will conflict with another upon persistence. This is used for such relationships that are truly capable of conflicting with each other on write, but the application will ensure that no such conflicts occur.

.. versionadded:: 1.4

.. seealso::

    :ref:`error_qzyx` - usage example

:param cascade: A comma-separated list of cascade rules which determines how Session operations should be "cascaded" from parent to child. This defaults to False, which means the default cascade should be used - this default cascade is "save-update, merge".

The available cascades are save-update, merge, expunge, delete, delete-orphan, and refresh-expire. An additional option, all indicates shorthand for "save-update, merge, refresh-expire, expunge, delete", and is often used as in "all, delete-orphan" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated.

.. seealso::

:ref:`unitofwork_cascades` - Full detail on each of the available
cascade options.

:param cascade_backrefs=False: Legacy; this flag is always False.

.. versionchanged:: 2.0 "cascade_backrefs" functionality has been removed.

:param collection_class: A class or callable that returns a new list-holding object. will be used in place of a plain list for storing elements.

.. seealso::

:ref:`custom_collections` - Introductory documentation and
examples.

:param comparator_factory: A class which extends :class:.Relationship.Comparator which provides custom SQL clause generation for comparison operations.

.. seealso::

:class:`.PropComparator` - some detail on redefining comparators
at this level.

:ref:`custom_comparators` - Brief intro to this feature.

:param distinct_target_key=None: Indicate if a "subquery" eager load should apply the DISTINCT keyword to the innermost SELECT statement. When left as None, the DISTINCT keyword will be applied in those cases when the target columns do not comprise the full primary key of the target table. When set to True, the DISTINCT keyword is applied to the innermost SELECT unconditionally.

It may be desirable to set this flag to False when the DISTINCT is reducing performance of the innermost subquery beyond that of what duplicate innermost rows may be causing.

.. seealso::

:ref:`loading_toplevel` - includes an introduction to subquery
eager loading.

:param doc: Docstring which will be applied to the resulting descriptor.

:param foreign_keys:

A list of columns which are to be used as "foreign key" columns, or columns which refer to the value in a remote column, within the context of this :func:_orm.relationship object's :paramref:_orm.relationship.primaryjoin condition. That is, if the :paramref:_orm.relationship.primaryjoin condition of this :func:_orm.relationship is a.id == b.a_id, and the values in b.a_id are required to be present in a.id, then the "foreign key" column of this :func:_orm.relationship is b.a_id.

In normal cases, the :paramref:_orm.relationship.foreign_keys parameter is not required. :func:_orm.relationship will automatically determine which columns in the :paramref:_orm.relationship.primaryjoin condition are to be considered "foreign key" columns based on those :class:_schema.Column objects that specify :class:_schema.ForeignKey, or are otherwise listed as referencing columns in a :class:_schema.ForeignKeyConstraint construct. :paramref:_orm.relationship.foreign_keys is only needed when:

1. There is more than one way to construct a join from the local
   table to the remote table, as there are multiple foreign key
   references present.  Setting ``foreign_keys`` will limit the
   :func:`_orm.relationship`
   to consider just those columns specified
   here as "foreign".

2. The :class:`_schema.Table` being mapped does not actually have
   :class:`_schema.ForeignKey` or
   :class:`_schema.ForeignKeyConstraint`
   constructs present, often because the table
   was reflected from a database that does not support foreign key
   reflection (MySQL MyISAM).

3. The :paramref:`_orm.relationship.primaryjoin`
   argument is used to
   construct a non-standard join condition, which makes use of
   columns or expressions that do not normally refer to their
   "parent" column, such as a join condition expressed by a
   complex comparison using a SQL function.

The :func:_orm.relationship construct will raise informative error messages that suggest the use of the :paramref:_orm.relationship.foreign_keys parameter when presented with an ambiguous condition. In typical cases, if :func:_orm.relationship doesn't raise any exceptions, the :paramref:_orm.relationship.foreign_keys parameter is usually not needed.

:paramref:_orm.relationship.foreign_keys may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

.. seealso::

:ref:`relationship_foreign_keys`

:ref:`relationship_custom_foreign`

:func:`.foreign` - allows direct annotation of the "foreign"
columns within a :paramref:`_orm.relationship.primaryjoin`
condition.

:param info: Optional data dictionary which will be populated into the :attr:.MapperProperty.info attribute of this object.

:param innerjoin=False: When True, joined eager loads will use an inner join to join against related tables instead of an outer join. The purpose of this option is generally one of performance, as inner joins generally perform better than outer joins.

This flag can be set to True when the relationship references an object via many-to-one using local foreign keys that are not nullable, or when the reference is one-to-one or a collection that is guaranteed to have one or at least one entry.

The option supports the same "nested" and "unnested" options as that of :paramref:_orm.joinedload.innerjoin. See that flag for details on nested / unnested behaviors.

.. seealso::

:paramref:`_orm.joinedload.innerjoin` - the option as specified by
loader option, including detail on nesting behavior.

:ref:`what_kind_of_loading` - Discussion of some details of
various loader options.

:param join_depth: When non-None, an integer value indicating how many levels deep "eager" loaders should join on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of None, eager loaders will stop chaining when they encounter a the same target mapper which is already higher up in the chain. This option applies both to joined- and subquery- eager loaders.

.. seealso::

:ref:`self_referential_eager_loading` - Introductory documentation
and examples.

:param lazy='select': specifies How the related items should be loaded. Default value is select. Values include:

  • select - items should be loaded lazily when the property is first accessed, using a separate SELECT statement, or identity map fetch for simple many-to-one references.

  • immediate - items should be loaded as the parents are loaded, using a separate SELECT statement, or identity map fetch for simple many-to-one references.

  • joined - items should be loaded "eagerly" in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is "outer" or not is determined by the :paramref:_orm.relationship.innerjoin parameter.

  • subquery - items should be loaded "eagerly" as the parents are loaded, using one additional SQL statement, which issues a JOIN to a subquery of the original statement, for each collection requested.

  • selectin - items should be loaded "eagerly" as the parents are loaded, using one or more additional SQL statements, which issues a JOIN to the immediate parent object, specifying primary key identifiers using an IN clause.

  • noload - no loading should occur at any time. The related collection will remain empty. The noload strategy is not recommended for general use. For a general use "never load" approach, see :ref:write_only_relationship

  • raise - lazy loading is disallowed; accessing the attribute, if its value were not already loaded via eager loading, will raise an :exc:~sqlalchemy.exc.InvalidRequestError. This strategy can be used when objects are to be detached from their attached :class:.Session after they are loaded.

  • raise_on_sql - lazy loading that emits SQL is disallowed; accessing the attribute, if its value were not already loaded via eager loading, will raise an :exc:~sqlalchemy.exc.InvalidRequestError, if the lazy load needs to emit SQL. If the lazy load can pull the related value from the identity map or determine that it should be None, the value is loaded. This strategy can be used when objects will remain associated with the attached :class:.Session, however additional SELECT statements should be blocked.

  • write_only - the attribute will be configured with a special "virtual collection" that may receive :meth:_orm.WriteOnlyCollection.add and :meth:_orm.WriteOnlyCollection.remove commands to add or remove individual objects, but will not under any circumstances load or iterate the full set of objects from the database directly. Instead, methods such as :meth:_orm.WriteOnlyCollection.select, :meth:_orm.WriteOnlyCollection.insert, :meth:_orm.WriteOnlyCollection.update and :meth:_orm.WriteOnlyCollection.delete are provided which generate SQL constructs that may be used to load and modify rows in bulk. Used for large collections that are never appropriate to load at once into memory.

    The write_only loader style is configured automatically when the :class:_orm.WriteOnlyMapped annotation is provided on the left hand side within a Declarative mapping. See the section :ref:write_only_relationship for examples.

    .. versionadded:: 2.0

    .. seealso::

    :ref:`write_only_relationship` - in the :ref:`queryguide_toplevel`
    
  • dynamic - the attribute will return a pre-configured :class:_query.Query object for all read operations, onto which further filtering operations can be applied before iterating the results.

    The dynamic loader style is configured automatically when the :class:_orm.DynamicMapped annotation is provided on the left hand side within a Declarative mapping. See the section :ref:dynamic_relationship for examples.

    .. legacy:: The "dynamic" lazy loader strategy is the legacy form of what is now the "write_only" strategy described in the section :ref:write_only_relationship.

    .. seealso::

    :ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel`
    
    :ref:`write_only_relationship` - more generally useful approach
    for large collections that should not fully load into memory
    
  • True - a synonym for 'select'

  • False - a synonym for 'joined'

  • None - a synonym for 'noload'

.. seealso::

:ref:`orm_queryguide_relationship_loaders` - Full documentation on
relationship loader configuration in the :ref:`queryguide_toplevel`.

:param load_on_pending=False: Indicates loading behavior for transient or pending parent objects.

When set to True, causes the lazy-loader to issue a query for a parent object that is not persistent, meaning it has never been flushed. This may take effect for a pending object when autoflush is disabled, or for a transient object that has been "attached" to a :class:.Session but is not part of its pending collection.

The :paramref:_orm.relationship.load_on_pending flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. This flag is not not intended for general use.

.. seealso::

  :meth:`.Session.enable_relationship_loading` - this method
  establishes "load on pending" behavior for the whole object, and
  also allows loading on objects that remain transient or
  detached.

:param order_by: Indicates the ordering that should be applied when loading these items. :paramref:_orm.relationship.order_by is expected to refer to one of the :class:_schema.Column objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column.

:paramref:_orm.relationship.order_by may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

:param passive_deletes=False: Indicates loading behavior during delete operations.

A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE rule is in place which will handle updating/deleting child rows on the database side.

Additionally, setting the flag to the string value 'all' will disable the "nulling out" of the child foreign keys, when the parent object is deleted and there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting. Additionally, the "nulling out" will still occur if the child object is de-associated with the parent.

.. seealso::

    :ref:`passive_deletes` - Introductory documentation
    and examples.

:param passive_updates=True: Indicates the persistence behavior to take when a referenced primary key value changes in place, indicating that the referencing foreign key columns will also need their value changed.

When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. When False, the SQLAlchemy :func:_orm.relationship construct will attempt to emit its own UPDATE statements to modify related targets. However note that SQLAlchemy cannot emit an UPDATE for more than one level of cascade. Also, setting this flag to False is not compatible in the case where the database is in fact enforcing referential integrity, unless those constraints are explicitly "deferred", if the target backend supports it.

It is highly advised that an application which is employing mutable primary keys keeps passive_updates set to True, and instead uses the referential integrity features of the database itself in order to handle the change efficiently and fully.

.. seealso::

  :ref:`passive_updates` - Introductory documentation and
  examples.

  :paramref:`.mapper.passive_updates` - a similar flag which
  takes effect for joined-table inheritance mappings.

:param post_update: This indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush operation returns an error that a "cyclical dependency" was detected, this is a cue that you might want to use :paramref:_orm.relationship.post_update to "break" the cycle.

.. seealso::

  :ref:`post_update` - Introductory documentation and examples.

:param primaryjoin: A SQL expression that will be used as the primary join of the child object against the parent object, or in a many-to-many relationship the join of the parent object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).

:paramref:_orm.relationship.primaryjoin may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

.. seealso::

  :ref:`relationship_primaryjoin`

:param remote_side: Used for self-referential relationships, indicates the column or list of columns that form the "remote side" of the relationship.

:paramref:_orm.relationship.remote_side may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

.. seealso::

:ref:`self_referential` - in-depth explanation of how
:paramref:`_orm.relationship.remote_side`
is used to configure self-referential relationships.

:func:`.remote` - an annotation function that accomplishes the
same purpose as :paramref:`_orm.relationship.remote_side`,
typically
when a custom :paramref:`_orm.relationship.primaryjoin` condition
is used.

:param query_class: A :class:_query.Query subclass that will be used internally by the AppenderQuery returned by a "dynamic" relationship, that is, a relationship that specifies lazy="dynamic" or was otherwise constructed using the :func:_orm.dynamic_loader function.

.. seealso::

:ref:`dynamic_relationship` - Introduction to "dynamic"
relationship loaders.

:param secondaryjoin: A SQL expression that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.

:paramref:_orm.relationship.secondaryjoin may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

.. warning:: When passed as a Python-evaluable string, the argument is interpreted using Python's eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See :ref:declarative_relationship_eval for details on declarative evaluation of :func:_orm.relationship arguments.

.. seealso::

  :ref:`relationship_primaryjoin`

:param single_parent: When True, installs a validator which will prevent objects from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage is optional, except for :func:_orm.relationship constructs which are many-to-one or many-to-many and also specify the delete-orphan cascade option. The :func:_orm.relationship construct itself will raise an error instructing when this option is required.

.. seealso::

:ref:`unitofwork_cascades` - includes detail on when the
:paramref:`_orm.relationship.single_parent`
flag may be appropriate.

:param uselist: A boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by :func:_orm.relationship at mapper configuration time. When using explicit :class:_orm.Mapped annotations, :paramref:_orm.relationship.uselist may be derived from the whether or not the annotation within :class:_orm.Mapped contains a collection class. Otherwise, :paramref:_orm.relationship.uselist may be derived from the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, use an appropriate :class:_orm.Mapped annotation or set :paramref:_orm.relationship.uselist to False.

The :paramref:_orm.relationship.uselist flag is also available on an existing :func:_orm.relationship construct as a read-only attribute, which can be used to determine if this :func:_orm.relationship deals with collections or scalar attributes::

  >>> User.addresses.property.uselist
  True

.. seealso::

  :ref:`relationships_one_to_one` - Introduction to the "one to
  one" relationship pattern, which is typically when an alternate
  setting for :paramref:`_orm.relationship.uselist` is involved.

:param viewonly=False: When set to True, the relationship is used only for loading objects, and not for any persistence operation. A :func:_orm.relationship which specifies :paramref:_orm.relationship.viewonly can work with a wider range of SQL operations within the :paramref:_orm.relationship.primaryjoin condition, including operations that feature the use of a variety of comparison operators as well as SQL functions such as :func:_expression.cast. The :paramref:_orm.relationship.viewonly flag is also of general use when defining any kind of :func:_orm.relationship that doesn't represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations.

.. seealso::

:ref:`relationship_viewonly_notes` - more details on best practices
when using :paramref:`_orm.relationship.viewonly`.

:param sync_backref: A boolean that enables the events used to synchronize the in-Python attributes when this relationship is target of either :paramref:_orm.relationship.backref or :paramref:_orm.relationship.back_populates.

Defaults to None, which indicates that an automatic value should be selected based on the value of the :paramref:_orm.relationship.viewonly flag. When left at its default, changes in state will be back-populated only if neither sides of a relationship is viewonly.

.. versionadded:: 1.3.17

.. versionchanged:: 1.4 - A relationship that specifies :paramref:_orm.relationship.viewonly automatically implies that :paramref:_orm.relationship.sync_backref is False.

.. seealso::

:paramref:`_orm.relationship.viewonly`

:param omit_join: Allows manual control over the "selectin" automatic join optimization. Set to False to disable the "omit join" feature added in SQLAlchemy 1.3; or leave as None to leave automatic optimization in place.

.. note:: This flag may only be set to False. It is not necessary to set it to True as the "omit_join" optimization is automatically detected; if it is not detected, then the optimization is not supported.

 .. versionchanged:: 1.3.11  setting ``omit_join`` to True will now
    emit a warning as this was not the intended use of this flag.

.. versionadded:: 1.3

:param init: Specific to :ref:orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __init__() method as generated by the dataclass process. :param repr: Specific to :ref:orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __repr__() method as generated by the dataclass process. :param default_factory: Specific to :ref:orm_declarative_native_dataclasses, specifies a default-value generation function that will take place as part of the __init__() method as generated by the dataclass process. :param compare: Specific to :ref:orm_declarative_native_dataclasses, indicates if this field should be included in comparison operations when generating the __eq__() and __ne__() methods for the mapped class.

.. versionadded:: 2.0.0b4

:param kw_only: Specific to :ref:orm_declarative_native_dataclasses, indicates if this field should be marked as keyword-only when generating the __init__().

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/_orm_constructors.py
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
def relationship(
    argument: Optional[_RelationshipArgumentType[Any]] = None,
    secondary: Optional[_RelationshipSecondaryArgument] = None,
    *,
    uselist: Optional[bool] = None,
    collection_class: Optional[
        Union[Type[Collection[Any]], Callable[[], Collection[Any]]]
    ] = None,
    primaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None,
    back_populates: Optional[str] = None,
    order_by: _ORMOrderByArgument = False,
    backref: Optional[ORMBackrefArgument] = None,
    overlaps: Optional[str] = None,
    post_update: bool = False,
    cascade: str = "save-update, merge",
    viewonly: bool = False,
    init: Union[_NoArg, bool] = _NoArg.NO_ARG,
    repr: Union[_NoArg, bool] = _NoArg.NO_ARG,  # noqa: A002
    default: Union[_NoArg, _T] = _NoArg.NO_ARG,
    default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG,
    compare: Union[_NoArg, bool] = _NoArg.NO_ARG,
    kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG,
    lazy: _LazyLoadArgumentType = "select",
    passive_deletes: Union[Literal["all"], bool] = False,
    passive_updates: bool = True,
    active_history: bool = False,
    enable_typechecks: bool = True,
    foreign_keys: Optional[_ORMColCollectionArgument] = None,
    remote_side: Optional[_ORMColCollectionArgument] = None,
    join_depth: Optional[int] = None,
    comparator_factory: Optional[
        Type[RelationshipProperty.Comparator[Any]]
    ] = None,
    single_parent: bool = False,
    innerjoin: bool = False,
    distinct_target_key: Optional[bool] = None,
    load_on_pending: bool = False,
    query_class: Optional[Type[Query[Any]]] = None,
    info: Optional[_InfoType] = None,
    omit_join: Literal[None, False] = None,
    sync_backref: Optional[bool] = None,
    **kw: Any,
) -> Relationship[Any]:
    """Provide a relationship between two mapped classes.

    This corresponds to a parent-child or associative table relationship.
    The constructed class is an instance of :class:`.Relationship`.

    .. seealso::

        :ref:`tutorial_orm_related_objects` - tutorial introduction
        to :func:`_orm.relationship` in the :ref:`unified_tutorial`

        :ref:`relationship_config_toplevel` - narrative documentation

    :param argument:
      This parameter refers to the class that is to be related.   It
      accepts several forms, including a direct reference to the target
      class itself, the :class:`_orm.Mapper` instance for the target class,
      a Python callable / lambda that will return a reference to the
      class or :class:`_orm.Mapper` when called, and finally a string
      name for the class, which will be resolved from the
      :class:`_orm.registry` in use in order to locate the class, e.g.::

            class SomeClass(Base):
                # ...

                related = relationship("RelatedClass")

      The :paramref:`_orm.relationship.argument` may also be omitted from the
      :func:`_orm.relationship` construct entirely, and instead placed inside
      a :class:`_orm.Mapped` annotation on the left side, which should
      include a Python collection type if the relationship is expected
      to be a collection, such as::

            class SomeClass(Base):
                # ...

                related_items: Mapped[List["RelatedItem"]] = relationship()

      Or for a many-to-one or one-to-one relationship::

            class SomeClass(Base):
                # ...

                related_item: Mapped["RelatedItem"] = relationship()

      .. seealso::

        :ref:`orm_declarative_properties` - further detail
        on relationship configuration when using Declarative.

    :param secondary:
      For a many-to-many relationship, specifies the intermediary
      table, and is typically an instance of :class:`_schema.Table`.
      In less common circumstances, the argument may also be specified
      as an :class:`_expression.Alias` construct, or even a
      :class:`_expression.Join` construct.

      :paramref:`_orm.relationship.secondary` may
      also be passed as a callable function which is evaluated at
      mapper initialization time.  When using Declarative, it may also
      be a string argument noting the name of a :class:`_schema.Table`
      that is
      present in the :class:`_schema.MetaData`
      collection associated with the
      parent-mapped :class:`_schema.Table`.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

      The :paramref:`_orm.relationship.secondary` keyword argument is
      typically applied in the case where the intermediary
      :class:`_schema.Table`
      is not otherwise expressed in any direct class mapping. If the
      "secondary" table is also explicitly mapped elsewhere (e.g. as in
      :ref:`association_pattern`), one should consider applying the
      :paramref:`_orm.relationship.viewonly` flag so that this
      :func:`_orm.relationship`
      is not used for persistence operations which
      may conflict with those of the association object pattern.

      .. seealso::

          :ref:`relationships_many_to_many` - Reference example of "many
          to many".

          :ref:`self_referential_many_to_many` - Specifics on using
          many-to-many in a self-referential case.

          :ref:`declarative_many_to_many` - Additional options when using
          Declarative.

          :ref:`association_pattern` - an alternative to
          :paramref:`_orm.relationship.secondary`
          when composing association
          table relationships, allowing additional attributes to be
          specified on the association table.

          :ref:`composite_secondary_join` - a lesser-used pattern which
          in some cases can enable complex :func:`_orm.relationship` SQL
          conditions to be used.

    :param active_history=False:
      When ``True``, indicates that the "previous" value for a
      many-to-one reference should be loaded when replaced, if
      not already loaded. Normally, history tracking logic for
      simple many-to-ones only needs to be aware of the "new"
      value in order to perform a flush. This flag is available
      for applications that make use of
      :func:`.attributes.get_history` which also need to know
      the "previous" value of the attribute.

    :param backref:
      A reference to a string relationship name, or a :func:`_orm.backref`
      construct, which will be used to automatically generate a new
      :func:`_orm.relationship` on the related class, which then refers to this
      one using a bi-directional :paramref:`_orm.relationship.back_populates`
      configuration.

      In modern Python, explicit use of :func:`_orm.relationship`
      with :paramref:`_orm.relationship.back_populates` should be preferred,
      as it is more robust in terms of mapper configuration as well as
      more conceptually straightforward.  It also integrates with
      new :pep:`484` typing features introduced in SQLAlchemy 2.0 which
      is not possible with dynamically generated attributes.

      .. seealso::

        :ref:`relationships_backref` - notes on using
        :paramref:`_orm.relationship.backref`

        :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
        presents an overview of bi-directional relationship configuration
        and behaviors using :paramref:`_orm.relationship.back_populates`

        :func:`.backref` - allows control over :func:`_orm.relationship`
        configuration when using :paramref:`_orm.relationship.backref`.


    :param back_populates:
      Indicates the name of a :func:`_orm.relationship` on the related
      class that will be synchronized with this one.   It is usually
      expected that the :func:`_orm.relationship` on the related class
      also refer to this one.  This allows objects on both sides of
      each :func:`_orm.relationship` to synchronize in-Python state
      changes and also provides directives to the :term:`unit of work`
      flush process how changes along these relationships should
      be persisted.

      .. seealso::

        :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`,
        presents an overview of bi-directional relationship configuration
        and behaviors.

        :ref:`relationship_patterns` - includes many examples of
        :paramref:`_orm.relationship.back_populates`.

        :paramref:`_orm.relationship.backref` - legacy form which allows
        more succinct configuration, but does not support explicit typing

    :param overlaps:
       A string name or comma-delimited set of names of other relationships
       on either this mapper, a descendant mapper, or a target mapper with
       which this relationship may write to the same foreign keys upon
       persistence.   The only effect this has is to eliminate the
       warning that this relationship will conflict with another upon
       persistence.   This is used for such relationships that are truly
       capable of conflicting with each other on write, but the application
       will ensure that no such conflicts occur.

       .. versionadded:: 1.4

       .. seealso::

            :ref:`error_qzyx` - usage example

    :param cascade:
      A comma-separated list of cascade rules which determines how
      Session operations should be "cascaded" from parent to child.
      This defaults to ``False``, which means the default cascade
      should be used - this default cascade is ``"save-update, merge"``.

      The available cascades are ``save-update``, ``merge``,
      ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``.
      An additional option, ``all`` indicates shorthand for
      ``"save-update, merge, refresh-expire,
      expunge, delete"``, and is often used as in ``"all, delete-orphan"``
      to indicate that related objects should follow along with the
      parent object in all cases, and be deleted when de-associated.

      .. seealso::

        :ref:`unitofwork_cascades` - Full detail on each of the available
        cascade options.

    :param cascade_backrefs=False:
      Legacy; this flag is always False.

      .. versionchanged:: 2.0 "cascade_backrefs" functionality has been
         removed.

    :param collection_class:
      A class or callable that returns a new list-holding object. will
      be used in place of a plain list for storing elements.

      .. seealso::

        :ref:`custom_collections` - Introductory documentation and
        examples.

    :param comparator_factory:
      A class which extends :class:`.Relationship.Comparator`
      which provides custom SQL clause generation for comparison
      operations.

      .. seealso::

        :class:`.PropComparator` - some detail on redefining comparators
        at this level.

        :ref:`custom_comparators` - Brief intro to this feature.


    :param distinct_target_key=None:
      Indicate if a "subquery" eager load should apply the DISTINCT
      keyword to the innermost SELECT statement.  When left as ``None``,
      the DISTINCT keyword will be applied in those cases when the target
      columns do not comprise the full primary key of the target table.
      When set to ``True``, the DISTINCT keyword is applied to the
      innermost SELECT unconditionally.

      It may be desirable to set this flag to False when the DISTINCT is
      reducing performance of the innermost subquery beyond that of what
      duplicate innermost rows may be causing.

      .. seealso::

        :ref:`loading_toplevel` - includes an introduction to subquery
        eager loading.

    :param doc:
      Docstring which will be applied to the resulting descriptor.

    :param foreign_keys:

      A list of columns which are to be used as "foreign key"
      columns, or columns which refer to the value in a remote
      column, within the context of this :func:`_orm.relationship`
      object's :paramref:`_orm.relationship.primaryjoin` condition.
      That is, if the :paramref:`_orm.relationship.primaryjoin`
      condition of this :func:`_orm.relationship` is ``a.id ==
      b.a_id``, and the values in ``b.a_id`` are required to be
      present in ``a.id``, then the "foreign key" column of this
      :func:`_orm.relationship` is ``b.a_id``.

      In normal cases, the :paramref:`_orm.relationship.foreign_keys`
      parameter is **not required.** :func:`_orm.relationship` will
      automatically determine which columns in the
      :paramref:`_orm.relationship.primaryjoin` condition are to be
      considered "foreign key" columns based on those
      :class:`_schema.Column` objects that specify
      :class:`_schema.ForeignKey`,
      or are otherwise listed as referencing columns in a
      :class:`_schema.ForeignKeyConstraint` construct.
      :paramref:`_orm.relationship.foreign_keys` is only needed when:

        1. There is more than one way to construct a join from the local
           table to the remote table, as there are multiple foreign key
           references present.  Setting ``foreign_keys`` will limit the
           :func:`_orm.relationship`
           to consider just those columns specified
           here as "foreign".

        2. The :class:`_schema.Table` being mapped does not actually have
           :class:`_schema.ForeignKey` or
           :class:`_schema.ForeignKeyConstraint`
           constructs present, often because the table
           was reflected from a database that does not support foreign key
           reflection (MySQL MyISAM).

        3. The :paramref:`_orm.relationship.primaryjoin`
           argument is used to
           construct a non-standard join condition, which makes use of
           columns or expressions that do not normally refer to their
           "parent" column, such as a join condition expressed by a
           complex comparison using a SQL function.

      The :func:`_orm.relationship` construct will raise informative
      error messages that suggest the use of the
      :paramref:`_orm.relationship.foreign_keys` parameter when
      presented with an ambiguous condition.   In typical cases,
      if :func:`_orm.relationship` doesn't raise any exceptions, the
      :paramref:`_orm.relationship.foreign_keys` parameter is usually
      not needed.

      :paramref:`_orm.relationship.foreign_keys` may also be passed as a
      callable function which is evaluated at mapper initialization time,
      and may be passed as a Python-evaluable string when using
      Declarative.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

      .. seealso::

        :ref:`relationship_foreign_keys`

        :ref:`relationship_custom_foreign`

        :func:`.foreign` - allows direct annotation of the "foreign"
        columns within a :paramref:`_orm.relationship.primaryjoin`
        condition.

    :param info: Optional data dictionary which will be populated into the
        :attr:`.MapperProperty.info` attribute of this object.

    :param innerjoin=False:
      When ``True``, joined eager loads will use an inner join to join
      against related tables instead of an outer join.  The purpose
      of this option is generally one of performance, as inner joins
      generally perform better than outer joins.

      This flag can be set to ``True`` when the relationship references an
      object via many-to-one using local foreign keys that are not
      nullable, or when the reference is one-to-one or a collection that
      is guaranteed to have one or at least one entry.

      The option supports the same "nested" and "unnested" options as
      that of :paramref:`_orm.joinedload.innerjoin`.  See that flag
      for details on nested / unnested behaviors.

      .. seealso::

        :paramref:`_orm.joinedload.innerjoin` - the option as specified by
        loader option, including detail on nesting behavior.

        :ref:`what_kind_of_loading` - Discussion of some details of
        various loader options.


    :param join_depth:
      When non-``None``, an integer value indicating how many levels
      deep "eager" loaders should join on a self-referring or cyclical
      relationship.  The number counts how many times the same Mapper
      shall be present in the loading condition along a particular join
      branch.  When left at its default of ``None``, eager loaders
      will stop chaining when they encounter a the same target mapper
      which is already higher up in the chain.  This option applies
      both to joined- and subquery- eager loaders.

      .. seealso::

        :ref:`self_referential_eager_loading` - Introductory documentation
        and examples.

    :param lazy='select': specifies
      How the related items should be loaded.  Default value is
      ``select``.  Values include:

      * ``select`` - items should be loaded lazily when the property is
        first accessed, using a separate SELECT statement, or identity map
        fetch for simple many-to-one references.

      * ``immediate`` - items should be loaded as the parents are loaded,
        using a separate SELECT statement, or identity map fetch for
        simple many-to-one references.

      * ``joined`` - items should be loaded "eagerly" in the same query as
        that of the parent, using a JOIN or LEFT OUTER JOIN.  Whether
        the join is "outer" or not is determined by the
        :paramref:`_orm.relationship.innerjoin` parameter.

      * ``subquery`` - items should be loaded "eagerly" as the parents are
        loaded, using one additional SQL statement, which issues a JOIN to
        a subquery of the original statement, for each collection
        requested.

      * ``selectin`` - items should be loaded "eagerly" as the parents
        are loaded, using one or more additional SQL statements, which
        issues a JOIN to the immediate parent object, specifying primary
        key identifiers using an IN clause.

      * ``noload`` - no loading should occur at any time.  The related
        collection will remain empty.   The ``noload`` strategy is not
        recommended for general use.  For a general use "never load"
        approach, see :ref:`write_only_relationship`

      * ``raise`` - lazy loading is disallowed; accessing
        the attribute, if its value were not already loaded via eager
        loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`.
        This strategy can be used when objects are to be detached from
        their attached :class:`.Session` after they are loaded.

      * ``raise_on_sql`` - lazy loading that emits SQL is disallowed;
        accessing the attribute, if its value were not already loaded via
        eager loading, will raise an
        :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load
        needs to emit SQL**.  If the lazy load can pull the related value
        from the identity map or determine that it should be None, the
        value is loaded.  This strategy can be used when objects will
        remain associated with the attached :class:`.Session`, however
        additional SELECT statements should be blocked.

      * ``write_only`` - the attribute will be configured with a special
        "virtual collection" that may receive
        :meth:`_orm.WriteOnlyCollection.add` and
        :meth:`_orm.WriteOnlyCollection.remove` commands to add or remove
        individual objects, but will not under any circumstances load or
        iterate the full set of objects from the database directly. Instead,
        methods such as :meth:`_orm.WriteOnlyCollection.select`,
        :meth:`_orm.WriteOnlyCollection.insert`,
        :meth:`_orm.WriteOnlyCollection.update` and
        :meth:`_orm.WriteOnlyCollection.delete` are provided which generate SQL
        constructs that may be used to load and modify rows in bulk. Used for
        large collections that are never appropriate to load at once into
        memory.

        The ``write_only`` loader style is configured automatically when
        the :class:`_orm.WriteOnlyMapped` annotation is provided on the
        left hand side within a Declarative mapping.  See the section
        :ref:`write_only_relationship` for examples.

        .. versionadded:: 2.0

        .. seealso::

            :ref:`write_only_relationship` - in the :ref:`queryguide_toplevel`

      * ``dynamic`` - the attribute will return a pre-configured
        :class:`_query.Query` object for all read
        operations, onto which further filtering operations can be
        applied before iterating the results.

        The ``dynamic`` loader style is configured automatically when
        the :class:`_orm.DynamicMapped` annotation is provided on the
        left hand side within a Declarative mapping.  See the section
        :ref:`dynamic_relationship` for examples.

        .. legacy::  The "dynamic" lazy loader strategy is the legacy form of
           what is now the "write_only" strategy described in the section
           :ref:`write_only_relationship`.

        .. seealso::

            :ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel`

            :ref:`write_only_relationship` - more generally useful approach
            for large collections that should not fully load into memory

      * True - a synonym for 'select'

      * False - a synonym for 'joined'

      * None - a synonym for 'noload'

      .. seealso::

        :ref:`orm_queryguide_relationship_loaders` - Full documentation on
        relationship loader configuration in the :ref:`queryguide_toplevel`.


    :param load_on_pending=False:
      Indicates loading behavior for transient or pending parent objects.

      When set to ``True``, causes the lazy-loader to
      issue a query for a parent object that is not persistent, meaning it
      has never been flushed.  This may take effect for a pending object
      when autoflush is disabled, or for a transient object that has been
      "attached" to a :class:`.Session` but is not part of its pending
      collection.

      The :paramref:`_orm.relationship.load_on_pending`
      flag does not improve
      behavior when the ORM is used normally - object references should be
      constructed at the object level, not at the foreign key level, so
      that they are present in an ordinary way before a flush proceeds.
      This flag is not not intended for general use.

      .. seealso::

          :meth:`.Session.enable_relationship_loading` - this method
          establishes "load on pending" behavior for the whole object, and
          also allows loading on objects that remain transient or
          detached.

    :param order_by:
      Indicates the ordering that should be applied when loading these
      items.  :paramref:`_orm.relationship.order_by`
      is expected to refer to
      one of the :class:`_schema.Column`
      objects to which the target class is
      mapped, or the attribute itself bound to the target class which
      refers to the column.

      :paramref:`_orm.relationship.order_by`
      may also be passed as a callable
      function which is evaluated at mapper initialization time, and may
      be passed as a Python-evaluable string when using Declarative.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

    :param passive_deletes=False:
       Indicates loading behavior during delete operations.

       A value of True indicates that unloaded child items should not
       be loaded during a delete operation on the parent.  Normally,
       when a parent item is deleted, all child items are loaded so
       that they can either be marked as deleted, or have their
       foreign key to the parent set to NULL.  Marking this flag as
       True usually implies an ON DELETE <CASCADE|SET NULL> rule is in
       place which will handle updating/deleting child rows on the
       database side.

       Additionally, setting the flag to the string value 'all' will
       disable the "nulling out" of the child foreign keys, when the parent
       object is deleted and there is no delete or delete-orphan cascade
       enabled.  This is typically used when a triggering or error raise
       scenario is in place on the database side.  Note that the foreign
       key attributes on in-session child objects will not be changed after
       a flush occurs so this is a very special use-case setting.
       Additionally, the "nulling out" will still occur if the child
       object is de-associated with the parent.

       .. seealso::

            :ref:`passive_deletes` - Introductory documentation
            and examples.

    :param passive_updates=True:
      Indicates the persistence behavior to take when a referenced
      primary key value changes in place, indicating that the referencing
      foreign key columns will also need their value changed.

      When True, it is assumed that ``ON UPDATE CASCADE`` is configured on
      the foreign key in the database, and that the database will
      handle propagation of an UPDATE from a source column to
      dependent rows.  When False, the SQLAlchemy
      :func:`_orm.relationship`
      construct will attempt to emit its own UPDATE statements to
      modify related targets.  However note that SQLAlchemy **cannot**
      emit an UPDATE for more than one level of cascade.  Also,
      setting this flag to False is not compatible in the case where
      the database is in fact enforcing referential integrity, unless
      those constraints are explicitly "deferred", if the target backend
      supports it.

      It is highly advised that an application which is employing
      mutable primary keys keeps ``passive_updates`` set to True,
      and instead uses the referential integrity features of the database
      itself in order to handle the change efficiently and fully.

      .. seealso::

          :ref:`passive_updates` - Introductory documentation and
          examples.

          :paramref:`.mapper.passive_updates` - a similar flag which
          takes effect for joined-table inheritance mappings.

    :param post_update:
      This indicates that the relationship should be handled by a
      second UPDATE statement after an INSERT or before a
      DELETE. This flag is used to handle saving bi-directional
      dependencies between two individual rows (i.e. each row
      references the other), where it would otherwise be impossible to
      INSERT or DELETE both rows fully since one row exists before the
      other. Use this flag when a particular mapping arrangement will
      incur two rows that are dependent on each other, such as a table
      that has a one-to-many relationship to a set of child rows, and
      also has a column that references a single child row within that
      list (i.e. both tables contain a foreign key to each other). If
      a flush operation returns an error that a "cyclical
      dependency" was detected, this is a cue that you might want to
      use :paramref:`_orm.relationship.post_update` to "break" the cycle.

      .. seealso::

          :ref:`post_update` - Introductory documentation and examples.

    :param primaryjoin:
      A SQL expression that will be used as the primary
      join of the child object against the parent object, or in a
      many-to-many relationship the join of the parent object to the
      association table. By default, this value is computed based on the
      foreign key relationships of the parent and child tables (or
      association table).

      :paramref:`_orm.relationship.primaryjoin` may also be passed as a
      callable function which is evaluated at mapper initialization time,
      and may be passed as a Python-evaluable string when using
      Declarative.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

      .. seealso::

          :ref:`relationship_primaryjoin`

    :param remote_side:
      Used for self-referential relationships, indicates the column or
      list of columns that form the "remote side" of the relationship.

      :paramref:`_orm.relationship.remote_side` may also be passed as a
      callable function which is evaluated at mapper initialization time,
      and may be passed as a Python-evaluable string when using
      Declarative.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

      .. seealso::

        :ref:`self_referential` - in-depth explanation of how
        :paramref:`_orm.relationship.remote_side`
        is used to configure self-referential relationships.

        :func:`.remote` - an annotation function that accomplishes the
        same purpose as :paramref:`_orm.relationship.remote_side`,
        typically
        when a custom :paramref:`_orm.relationship.primaryjoin` condition
        is used.

    :param query_class:
      A :class:`_query.Query`
      subclass that will be used internally by the
      ``AppenderQuery`` returned by a "dynamic" relationship, that
      is, a relationship that specifies ``lazy="dynamic"`` or was
      otherwise constructed using the :func:`_orm.dynamic_loader`
      function.

      .. seealso::

        :ref:`dynamic_relationship` - Introduction to "dynamic"
        relationship loaders.

    :param secondaryjoin:
      A SQL expression that will be used as the join of
      an association table to the child object. By default, this value is
      computed based on the foreign key relationships of the association
      and child tables.

      :paramref:`_orm.relationship.secondaryjoin` may also be passed as a
      callable function which is evaluated at mapper initialization time,
      and may be passed as a Python-evaluable string when using
      Declarative.

      .. warning:: When passed as a Python-evaluable string, the
         argument is interpreted using Python's ``eval()`` function.
         **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
         See :ref:`declarative_relationship_eval` for details on
         declarative evaluation of :func:`_orm.relationship` arguments.

      .. seealso::

          :ref:`relationship_primaryjoin`

    :param single_parent:
      When True, installs a validator which will prevent objects
      from being associated with more than one parent at a time.
      This is used for many-to-one or many-to-many relationships that
      should be treated either as one-to-one or one-to-many.  Its usage
      is optional, except for :func:`_orm.relationship` constructs which
      are many-to-one or many-to-many and also
      specify the ``delete-orphan`` cascade option.  The
      :func:`_orm.relationship` construct itself will raise an error
      instructing when this option is required.

      .. seealso::

        :ref:`unitofwork_cascades` - includes detail on when the
        :paramref:`_orm.relationship.single_parent`
        flag may be appropriate.

    :param uselist:
      A boolean that indicates if this property should be loaded as a
      list or a scalar. In most cases, this value is determined
      automatically by :func:`_orm.relationship` at mapper configuration
      time.  When using explicit :class:`_orm.Mapped` annotations,
      :paramref:`_orm.relationship.uselist` may be derived from the
      whether or not the annotation within :class:`_orm.Mapped` contains
      a collection class.
      Otherwise, :paramref:`_orm.relationship.uselist` may be derived from
      the type and direction
      of the relationship - one to many forms a list, many to one
      forms a scalar, many to many is a list. If a scalar is desired
      where normally a list would be present, such as a bi-directional
      one-to-one relationship, use an appropriate :class:`_orm.Mapped`
      annotation or set :paramref:`_orm.relationship.uselist` to False.

      The :paramref:`_orm.relationship.uselist`
      flag is also available on an
      existing :func:`_orm.relationship`
      construct as a read-only attribute,
      which can be used to determine if this :func:`_orm.relationship`
      deals
      with collections or scalar attributes::

          >>> User.addresses.property.uselist
          True

      .. seealso::

          :ref:`relationships_one_to_one` - Introduction to the "one to
          one" relationship pattern, which is typically when an alternate
          setting for :paramref:`_orm.relationship.uselist` is involved.

    :param viewonly=False:
      When set to ``True``, the relationship is used only for loading
      objects, and not for any persistence operation.  A
      :func:`_orm.relationship` which specifies
      :paramref:`_orm.relationship.viewonly` can work
      with a wider range of SQL operations within the
      :paramref:`_orm.relationship.primaryjoin` condition, including
      operations that feature the use of a variety of comparison operators
      as well as SQL functions such as :func:`_expression.cast`.  The
      :paramref:`_orm.relationship.viewonly`
      flag is also of general use when defining any kind of
      :func:`_orm.relationship` that doesn't represent
      the full set of related objects, to prevent modifications of the
      collection from resulting in persistence operations.

      .. seealso::

        :ref:`relationship_viewonly_notes` - more details on best practices
        when using :paramref:`_orm.relationship.viewonly`.

    :param sync_backref:
      A boolean that enables the events used to synchronize the in-Python
      attributes when this relationship is target of either
      :paramref:`_orm.relationship.backref` or
      :paramref:`_orm.relationship.back_populates`.

      Defaults to ``None``, which indicates that an automatic value should
      be selected based on the value of the
      :paramref:`_orm.relationship.viewonly` flag.  When left at its
      default, changes in state will be back-populated only if neither
      sides of a relationship is viewonly.

      .. versionadded:: 1.3.17

      .. versionchanged:: 1.4 - A relationship that specifies
         :paramref:`_orm.relationship.viewonly` automatically implies
         that :paramref:`_orm.relationship.sync_backref` is ``False``.

      .. seealso::

        :paramref:`_orm.relationship.viewonly`

    :param omit_join:
      Allows manual control over the "selectin" automatic join
      optimization.  Set to ``False`` to disable the "omit join" feature
      added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic
      optimization in place.

      .. note:: This flag may only be set to ``False``.   It is not
         necessary to set it to ``True`` as the "omit_join" optimization is
         automatically detected; if it is not detected, then the
         optimization is not supported.

         .. versionchanged:: 1.3.11  setting ``omit_join`` to True will now
            emit a warning as this was not the intended use of this flag.

      .. versionadded:: 1.3

    :param init: Specific to :ref:`orm_declarative_native_dataclasses`,
     specifies if the mapped attribute should be part of the ``__init__()``
     method as generated by the dataclass process.
    :param repr: Specific to :ref:`orm_declarative_native_dataclasses`,
     specifies if the mapped attribute should be part of the ``__repr__()``
     method as generated by the dataclass process.
    :param default_factory: Specific to
     :ref:`orm_declarative_native_dataclasses`,
     specifies a default-value generation function that will take place
     as part of the ``__init__()``
     method as generated by the dataclass process.
    :param compare: Specific to
     :ref:`orm_declarative_native_dataclasses`, indicates if this field
     should be included in comparison operations when generating the
     ``__eq__()`` and ``__ne__()`` methods for the mapped class.

     .. versionadded:: 2.0.0b4

    :param kw_only: Specific to
     :ref:`orm_declarative_native_dataclasses`, indicates if this field
     should be marked as keyword-only when generating the ``__init__()``.


    """

    return Relationship(
        argument,
        secondary=secondary,
        uselist=uselist,
        collection_class=collection_class,
        primaryjoin=primaryjoin,
        secondaryjoin=secondaryjoin,
        back_populates=back_populates,
        order_by=order_by,
        backref=backref,
        overlaps=overlaps,
        post_update=post_update,
        cascade=cascade,
        viewonly=viewonly,
        attribute_options=_AttributeOptions(
            init, repr, default, default_factory, compare, kw_only
        ),
        lazy=lazy,
        passive_deletes=passive_deletes,
        passive_updates=passive_updates,
        active_history=active_history,
        enable_typechecks=enable_typechecks,
        foreign_keys=foreign_keys,
        remote_side=remote_side,
        join_depth=join_depth,
        comparator_factory=comparator_factory,
        single_parent=single_parent,
        innerjoin=innerjoin,
        distinct_target_key=distinct_target_key,
        load_on_pending=load_on_pending,
        query_class=query_class,
        info=info,
        omit_join=omit_join,
        sync_backref=sync_backref,
        **kw,
    )

contains_eager

contains_eager(
    *keys: _AttrType, **kw: Any
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def contains_eager(*keys: _AttrType, **kw: Any) -> _AbstractLoad:
    return _generate_from_keys(Load.contains_eager, keys, True, kw)

defaultload

defaultload(*keys: _AttrType) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def defaultload(*keys: _AttrType) -> _AbstractLoad:
    return _generate_from_keys(Load.defaultload, keys, False, {})

defer

defer(
    key: _AttrType,
    *addl_attrs: _AttrType,
    raiseload: bool = False,
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def defer(
    key: _AttrType, *addl_attrs: _AttrType, raiseload: bool = False
) -> _AbstractLoad:
    if addl_attrs:
        util.warn_deprecated(
            "The *addl_attrs on orm.defer is deprecated.  Please use "
            "method chaining in conjunction with defaultload() to "
            "indicate a path.",
            version="1.3",
        )

    if raiseload:
        kw = {"raiseload": raiseload}
    else:
        kw = {}

    return _generate_from_keys(Load.defer, (key,) + addl_attrs, False, kw)

immediateload

immediateload(
    *keys: _AttrType, recursion_depth: Optional[int] = None
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def immediateload(
    *keys: _AttrType, recursion_depth: Optional[int] = None
) -> _AbstractLoad:
    return _generate_from_keys(
        Load.immediateload, keys, False, {"recursion_depth": recursion_depth}
    )

is_instrumented

is_instrumented(instance, key)

Return True if the given attribute on the given instance is instrumented by the attributes package.

This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/instrumentation.py
def is_instrumented(instance, key):
    """Return True if the given attribute on the given instance is
    instrumented by the attributes package.

    This function may be used regardless of instrumentation
    applied directly to the class, i.e. no descriptors are required.

    """
    return manager_of_class(instance.__class__).is_instrumented(
        key, search=True
    )

joinedload

joinedload(*keys: _AttrType, **kw: Any) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def joinedload(*keys: _AttrType, **kw: Any) -> _AbstractLoad:
    return _generate_from_keys(Load.joinedload, keys, False, kw)

lazyload

lazyload(*keys: _AttrType) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def lazyload(*keys: _AttrType) -> _AbstractLoad:
    return _generate_from_keys(Load.lazyload, keys, False, {})

load_only

load_only(
    *attrs: _AttrType, raiseload: bool = False
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def load_only(*attrs: _AttrType, raiseload: bool = False) -> _AbstractLoad:
    # TODO: attrs against different classes.  we likely have to
    # add some extra state to Load of some kind
    _, lead_element, _ = _parse_attr_argument(attrs[0])
    return Load(lead_element).load_only(*attrs, raiseload=raiseload)

make_transient

make_transient(instance: object) -> None

Alter the state of the given instance so that it is :term:transient.

.. note::

:func:`.make_transient` is a special-case function for
advanced use cases only.

The given mapped instance is assumed to be in the :term:persistent or :term:detached state. The function will remove its association with any :class:.Session as well as its :attr:.InstanceState.identity. The effect is that the object will behave as though it were newly constructed, except retaining any attribute / collection values that were loaded at the time of the call. The :attr:.InstanceState.deleted flag is also reset if this object had been deleted as a result of using :meth:.Session.delete.

.. warning::

:func:`.make_transient` does **not** "unexpire" or otherwise eagerly
load ORM-mapped attributes that are not currently loaded at the time
the function is called.   This includes attributes which:

* were expired via :meth:`.Session.expire`

* were expired as the natural effect of committing a session
  transaction, e.g. :meth:`.Session.commit`

* are normally :term:`lazy loaded` but are not currently loaded

* are "deferred" (see :ref:`orm_queryguide_column_deferral`) and are
  not yet loaded

* were not present in the query which loaded this object, such as that
  which is common in joined table inheritance and other scenarios.

After :func:`.make_transient` is called, unloaded attributes such
as those above will normally resolve to the value ``None`` when
accessed, or an empty collection for a collection-oriented attribute.
As the object is transient and un-associated with any database
identity, it will no longer retrieve these values.

.. seealso::

:func:`.make_transient_to_detached`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
def make_transient(instance: object) -> None:
    """Alter the state of the given instance so that it is :term:`transient`.

    .. note::

        :func:`.make_transient` is a special-case function for
        advanced use cases only.

    The given mapped instance is assumed to be in the :term:`persistent` or
    :term:`detached` state.   The function will remove its association with any
    :class:`.Session` as well as its :attr:`.InstanceState.identity`. The
    effect is that the object will behave as though it were newly constructed,
    except retaining any attribute / collection values that were loaded at the
    time of the call.   The :attr:`.InstanceState.deleted` flag is also reset
    if this object had been deleted as a result of using
    :meth:`.Session.delete`.

    .. warning::

        :func:`.make_transient` does **not** "unexpire" or otherwise eagerly
        load ORM-mapped attributes that are not currently loaded at the time
        the function is called.   This includes attributes which:

        * were expired via :meth:`.Session.expire`

        * were expired as the natural effect of committing a session
          transaction, e.g. :meth:`.Session.commit`

        * are normally :term:`lazy loaded` but are not currently loaded

        * are "deferred" (see :ref:`orm_queryguide_column_deferral`) and are
          not yet loaded

        * were not present in the query which loaded this object, such as that
          which is common in joined table inheritance and other scenarios.

        After :func:`.make_transient` is called, unloaded attributes such
        as those above will normally resolve to the value ``None`` when
        accessed, or an empty collection for a collection-oriented attribute.
        As the object is transient and un-associated with any database
        identity, it will no longer retrieve these values.

    .. seealso::

        :func:`.make_transient_to_detached`

    """
    state = attributes.instance_state(instance)
    s = _state_session(state)
    if s:
        s._expunge_states([state])

    # remove expired state
    state.expired_attributes.clear()

    # remove deferred callables
    if state.callables:
        del state.callables

    if state.key:
        del state.key
    if state._deleted:
        del state._deleted

make_transient_to_detached

make_transient_to_detached(instance: object) -> None

Make the given transient instance :term:detached.

.. note::

:func:`.make_transient_to_detached` is a special-case function for
advanced use cases only.

All attribute history on the given instance will be reset as though the instance were freshly loaded from a query. Missing attributes will be marked as expired. The primary key attributes of the object, which are required, will be made into the "key" of the instance.

The object can then be added to a session, or merged possibly with the load=False flag, at which point it will look as if it were loaded that way, without emitting SQL.

This is a special use case function that differs from a normal call to :meth:.Session.merge in that a given persistent state can be manufactured without any SQL calls.

.. seealso::

:func:`.make_transient`

:meth:`.Session.enable_relationship_loading`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
def make_transient_to_detached(instance: object) -> None:
    """Make the given transient instance :term:`detached`.

    .. note::

        :func:`.make_transient_to_detached` is a special-case function for
        advanced use cases only.

    All attribute history on the given instance
    will be reset as though the instance were freshly loaded
    from a query.  Missing attributes will be marked as expired.
    The primary key attributes of the object, which are required, will be made
    into the "key" of the instance.

    The object can then be added to a session, or merged
    possibly with the load=False flag, at which point it will look
    as if it were loaded that way, without emitting SQL.

    This is a special use case function that differs from a normal
    call to :meth:`.Session.merge` in that a given persistent state
    can be manufactured without any SQL calls.

    .. seealso::

        :func:`.make_transient`

        :meth:`.Session.enable_relationship_loading`

    """
    state = attributes.instance_state(instance)
    if state.session_id or state.key:
        raise sa_exc.InvalidRequestError("Given object must be transient")
    state.key = state.mapper._identity_key_from_state(state)
    if state._deleted:
        del state._deleted
    state._commit_all(state.dict)
    state._expire_attributes(state.dict, state.unloaded)

noload

noload(*keys: _AttrType) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def noload(*keys: _AttrType) -> _AbstractLoad:
    return _generate_from_keys(Load.noload, keys, False, {})

raiseload

raiseload(*keys: _AttrType, **kw: Any) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def raiseload(*keys: _AttrType, **kw: Any) -> _AbstractLoad:
    return _generate_from_keys(Load.raiseload, keys, False, kw)

selectin_polymorphic

selectin_polymorphic(
    base_cls: _EntityType[Any], classes: Iterable[Type[Any]]
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def selectin_polymorphic(
    base_cls: _EntityType[Any], classes: Iterable[Type[Any]]
) -> _AbstractLoad:
    ul = Load(base_cls)
    return ul.selectin_polymorphic(classes)

selectinload

selectinload(
    *keys: _AttrType, recursion_depth: Optional[int] = None
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def selectinload(
    *keys: _AttrType, recursion_depth: Optional[int] = None
) -> _AbstractLoad:
    return _generate_from_keys(
        Load.selectinload, keys, False, {"recursion_depth": recursion_depth}
    )

subqueryload

subqueryload(*keys: _AttrType) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def subqueryload(*keys: _AttrType) -> _AbstractLoad:
    return _generate_from_keys(Load.subqueryload, keys, False, {})

undefer

undefer(
    key: _AttrType, *addl_attrs: _AttrType
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def undefer(key: _AttrType, *addl_attrs: _AttrType) -> _AbstractLoad:
    if addl_attrs:
        util.warn_deprecated(
            "The *addl_attrs on orm.undefer is deprecated.  Please use "
            "method chaining in conjunction with defaultload() to "
            "indicate a path.",
            version="1.3",
        )
    return _generate_from_keys(Load.undefer, (key,) + addl_attrs, False, {})

undefer_group

undefer_group(name: str) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def undefer_group(name: str) -> _AbstractLoad:
    element = _WildcardLoad()
    return element.undefer_group(name)

with_expression

with_expression(
    key: _AttrType,
    expression: _ColumnExpressionArgument[Any],
) -> _AbstractLoad
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/strategy_options.py
@loader_unbound_fn
def with_expression(
    key: _AttrType, expression: _ColumnExpressionArgument[Any]
) -> _AbstractLoad:
    return _generate_from_keys(
        Load.with_expression, (key,), False, {"expression": expression}
    )

with_polymorphic

with_polymorphic(
    base: Union[Type[_O], Mapper[_O]],
    classes: Union[Literal["*"], Iterable[Type[Any]]],
    selectable: Union[
        Literal[False, None], FromClause
    ] = False,
    flat: bool = False,
    polymorphic_on: Optional[ColumnElement[Any]] = None,
    aliased: bool = False,
    innerjoin: bool = False,
    adapt_on_names: bool = False,
    _use_mapper_path: bool = False,
) -> AliasedClass[_O]

Produce an :class:.AliasedClass construct which specifies columns for descendant mappers of the given base.

Using this method will ensure that each descendant mapper's tables are included in the FROM clause, and will allow filter() criterion to be used against those tables. The resulting instances will also have those columns already loaded so that no "post fetch" of those columns will be required.

.. seealso::

:ref:`with_polymorphic` - full discussion of
:func:`_orm.with_polymorphic`.

:param base: Base class to be aliased.

:param classes: a single class or mapper, or list of class/mappers, which inherit from the base class. Alternatively, it may also be the string '*', in which case all descending mapped classes will be added to the FROM clause.

:param aliased: when True, the selectable will be aliased. For a JOIN, this means the JOIN will be SELECTed from inside of a subquery unless the :paramref:_orm.with_polymorphic.flat flag is set to True, which is recommended for simpler use cases.

:param flat: Boolean, will be passed through to the :meth:_expression.FromClause.alias call so that aliases of :class:_expression.Join objects will alias the individual tables inside the join, rather than creating a subquery. This is generally supported by all modern databases with regards to right-nested joins and generally produces more efficient queries. Setting this flag is recommended as long as the resulting SQL is functional.

:param selectable: a table or subquery that will be used in place of the generated FROM clause. This argument is required if any of the desired classes use concrete table inheritance, since SQLAlchemy currently cannot generate UNIONs among tables automatically. If used, the selectable argument must represent the full set of tables and columns mapped by every mapped class. Otherwise, the unaccounted mapped columns will result in their table being appended directly to the FROM clause which will usually lead to incorrect results.

When left at its default value of ``False``, the polymorphic
selectable assigned to the base mapper is used for selecting rows.
However, it may also be passed as ``None``, which will bypass the
configured polymorphic selectable and instead construct an ad-hoc
selectable for the target classes given; for joined table inheritance
this will be a join that includes all target mappers and their
subclasses.

:param polymorphic_on: a column to be used as the "discriminator" column for the given selectable. If not given, the polymorphic_on attribute of the base classes' mapper will be used, if any. This is useful for mappings that don't have polymorphic loading behavior by default.

:param innerjoin: if True, an INNER JOIN will be used. This should only be specified if querying for one specific subtype only

:param adapt_on_names: Passes through the :paramref:_orm.aliased.adapt_on_names parameter to the aliased object. This may be useful in situations where the given selectable is not directly related to the existing mapped selectable.

.. versionadded:: 1.4.33

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/_orm_constructors.py
def with_polymorphic(
    base: Union[Type[_O], Mapper[_O]],
    classes: Union[Literal["*"], Iterable[Type[Any]]],
    selectable: Union[Literal[False, None], FromClause] = False,
    flat: bool = False,
    polymorphic_on: Optional[ColumnElement[Any]] = None,
    aliased: bool = False,
    innerjoin: bool = False,
    adapt_on_names: bool = False,
    _use_mapper_path: bool = False,
) -> AliasedClass[_O]:
    """Produce an :class:`.AliasedClass` construct which specifies
    columns for descendant mappers of the given base.

    Using this method will ensure that each descendant mapper's
    tables are included in the FROM clause, and will allow filter()
    criterion to be used against those tables.  The resulting
    instances will also have those columns already loaded so that
    no "post fetch" of those columns will be required.

    .. seealso::

        :ref:`with_polymorphic` - full discussion of
        :func:`_orm.with_polymorphic`.

    :param base: Base class to be aliased.

    :param classes: a single class or mapper, or list of
        class/mappers, which inherit from the base class.
        Alternatively, it may also be the string ``'*'``, in which case
        all descending mapped classes will be added to the FROM clause.

    :param aliased: when True, the selectable will be aliased.   For a
        JOIN, this means the JOIN will be SELECTed from inside of a subquery
        unless the :paramref:`_orm.with_polymorphic.flat` flag is set to
        True, which is recommended for simpler use cases.

    :param flat: Boolean, will be passed through to the
     :meth:`_expression.FromClause.alias` call so that aliases of
     :class:`_expression.Join` objects will alias the individual tables
     inside the join, rather than creating a subquery.  This is generally
     supported by all modern databases with regards to right-nested joins
     and generally produces more efficient queries.  Setting this flag is
     recommended as long as the resulting SQL is functional.

    :param selectable: a table or subquery that will
        be used in place of the generated FROM clause. This argument is
        required if any of the desired classes use concrete table
        inheritance, since SQLAlchemy currently cannot generate UNIONs
        among tables automatically. If used, the ``selectable`` argument
        must represent the full set of tables and columns mapped by every
        mapped class. Otherwise, the unaccounted mapped columns will
        result in their table being appended directly to the FROM clause
        which will usually lead to incorrect results.

        When left at its default value of ``False``, the polymorphic
        selectable assigned to the base mapper is used for selecting rows.
        However, it may also be passed as ``None``, which will bypass the
        configured polymorphic selectable and instead construct an ad-hoc
        selectable for the target classes given; for joined table inheritance
        this will be a join that includes all target mappers and their
        subclasses.

    :param polymorphic_on: a column to be used as the "discriminator"
        column for the given selectable. If not given, the polymorphic_on
        attribute of the base classes' mapper will be used, if any. This
        is useful for mappings that don't have polymorphic loading
        behavior by default.

    :param innerjoin: if True, an INNER JOIN will be used.  This should
       only be specified if querying for one specific subtype only

    :param adapt_on_names: Passes through the
      :paramref:`_orm.aliased.adapt_on_names`
      parameter to the aliased object.  This may be useful in situations where
      the given selectable is not directly related to the existing mapped
      selectable.

      .. versionadded:: 1.4.33

    """
    return AliasedInsp._with_polymorphic_factory(
        base,
        classes,
        selectable=selectable,
        flat=flat,
        polymorphic_on=polymorphic_on,
        adapt_on_names=adapt_on_names,
        aliased=aliased,
        innerjoin=innerjoin,
        _use_mapper_path=_use_mapper_path,
    )