class documentation

Undocumented

Method contains_eager Indicate that the given attribute should be eagerly loaded from columns stated manually in the query.
Method defaultload Indicate an attribute should load using its default loader style.
Method defer Indicate that the given column-oriented attribute should be deferred, e.g. not loaded until accessed.
Method immediateload Indicate that the given attribute should be loaded using an immediate load with a per-attribute SELECT statement.
Method joinedload Indicate that the given attribute should be loaded using joined eager loading.
Method lazyload Indicate that the given attribute should be loaded using "lazy" loading.
Method load_only Indicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred.
Method noload Indicate that the given relationship attribute should remain unloaded.
Method options Apply a series of options as sub-options to this :class:`_orm._AbstractLoad` object.
Method process_compile_state Apply a modification to a given :class:`.ORMCompileState`.
Method process_compile_state_replaced_entities Apply a modification to a given :class:`.ORMCompileState`, given entities that were replaced by with_only_columns() or with_entities().
Method raiseload Indicate that the given attribute should raise an error if accessed.
Method selectin_polymorphic Indicate an eager load should take place for all attributes specific to a subclass.
Method selectinload Indicate that the given attribute should be loaded using SELECT IN eager loading.
Method subqueryload Indicate that the given attribute should be loaded using subquery eager loading.
Method undefer Indicate that the given column-oriented attribute should be undeferred, e.g. specified within the SELECT statement of the entity as a whole.
Method undefer_group Indicate that columns within the given deferred group name should be undeferred.
Method with_expression Apply an ad-hoc SQL expression to a "deferred expression" attribute.
Class Variable __slots__ Undocumented
Class Variable propagate_to_loaders 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.
Class Method _chop_path Undocumented
Method _apply_to_parent apply this :class:`_orm._AbstractLoad` object as a sub-option o a :class:`_orm.Load` object.
Method _clone_for_bind_strategy Undocumented
Method _coerce_strat Undocumented
Method _process implemented by subclasses
Method _set_class_strategy Undocumented
Method _set_column_strategy Undocumented
Method _set_generic_strategy Undocumented
Method _set_relationship_strategy Undocumented
Class Variable _is_strategy_option Undocumented

Inherited from GenerativeOnTraversal:

Method _generate Undocumented

Inherited from HasShallowCopy (via GenerativeOnTraversal):

Class Method _generate_shallow_copy Undocumented
Class Method _generate_shallow_from_dict Undocumented
Class Method _generate_shallow_to_dict Undocumented
Method _clone Create a shallow copy
Method _generated_shallow_copy_traversal Undocumented
Method _generated_shallow_from_dict_traversal Undocumented
Method _generated_shallow_to_dict_traversal Undocumented
Method _shallow_copy_to Undocumented
Method _shallow_from_dict Undocumented
Method _shallow_to_dict Undocumented

Inherited from CompileStateOption (via GenerativeOnTraversal, HasShallowCopy, LoaderOption):

Class Variable _is_compile_state Undocumented

Inherited from HasCacheKey (via GenerativeOnTraversal, HasShallowCopy, LoaderOption, CompileStateOption):

Class Variable inherit_cache Indicate if this :class:`.HasCacheKey` instance should make use of the cache key generation scheme used by its immediate superclass.
Class Method _generate_cache_attrs generate cache key dispatcher for a new class.
Class Method _generate_cache_key_for_object Undocumented
Method _gen_cache_key return an optional cache key.
Method _generate_cache_key return a cache key.
Class Variable _generated_cache_key_traversal Undocumented
Class Variable _hierarchy_supports_caching private attribute which may be set to False to prevent the inherit_cache warning from being emitted for a hierarchy of subclasses.
Class Variable _is_has_cache_key Undocumented

Inherited from ORMOption (via GenerativeOnTraversal, HasShallowCopy, LoaderOption, CompileStateOption, HasCacheKey):

Method _adapt_cached_option_to_uncached_option adapt this option to the "uncached" version of itself in a loader strategy context.
Class Variable _is_core Undocumented
Class Variable _is_criteria_option Undocumented
Class Variable _is_legacy_option Undocumented
Class Variable _is_user_defined Undocumented

Inherited from ExecutableOption (via GenerativeOnTraversal, HasShallowCopy, LoaderOption, CompileStateOption, HasCacheKey, ORMOption):

Class Variable __visit_name__ Undocumented

Inherited from HasCopyInternals (via GenerativeOnTraversal, HasShallowCopy, LoaderOption, CompileStateOption, HasCacheKey, ORMOption, ExecutableOption):

Method _copy_internals Reassign internal elements to be clones of themselves.

Inherited from HasTraverseInternals (via GenerativeOnTraversal, HasShallowCopy, LoaderOption, CompileStateOption, HasCacheKey, ORMOption, ExecutableOption, HasCopyInternals):

Method get_children Return immediate child :class:`.visitors.HasTraverseInternals` elements of this :class:`.visitors.HasTraverseInternals`.
Class Variable _is_immutable Undocumented
Class Variable _traverse_internals Undocumented
def contains_eager(self, attr: _AttrType, alias: Optional[_FromClauseArgument] = None, _is_chain: bool = False) -> Self: (source)

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`

def defaultload(self, attr: _AttrType) -> Self: (source)

Indicate an attribute should load using its default loader style. 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`

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

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`

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

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`

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

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. .. versionchanged:: 1.0.0 ``innerjoin=True`` now implies ``innerjoin="nested"``, whereas in 0.9 it implied ``innerjoin="unnested"``. In order to achieve the pre-1.0 "unnested" inner join behavior, use the value ``innerjoin="unnested"``. See :ref:`migration_3008`. .. 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`

def lazyload(self, attr: _AttrType) -> Self: (source)

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`

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

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

def noload(self, attr: _AttrType) -> Self: (source)

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`

def options(self, *opts: _AbstractLoad) -> Self: (source)

Apply a series of options as sub-options to this :class:`_orm._AbstractLoad` object. Implementation is provided by subclasses.

def process_compile_state(self, compile_state: ORMCompileState): (source)

Apply a modification to a given :class:`.ORMCompileState`. This method is part of the implementation of a particular :class:`.CompileStateOption` and is only invoked internally when an ORM query is compiled.

def process_compile_state_replaced_entities(self, compile_state: ORMCompileState, mapper_entities: Sequence[_MapperEntity]): (source)

Apply a modification to a given :class:`.ORMCompileState`, given entities that were replaced by with_only_columns() or with_entities(). This method is part of the implementation of a particular :class:`.CompileStateOption` and is only invoked internally when an ORM query is compiled. .. versionadded:: 1.4.19

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

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. .. versionadded:: 1.1 .. seealso:: :ref:`loading_toplevel` :ref:`prevent_lazy_with_raiseload` :ref:`orm_queryguide_deferred_raiseload`

def selectin_polymorphic(self, classes: Iterable[Type[Any]]) -> Self: (source)

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`

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

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`

def subqueryload(self, attr: _AttrType) -> Self: (source)

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`

def undefer(self, key: _AttrType) -> Self: (source)

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`

def undefer_group(self, name: str) -> Self: (source)

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`

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

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

propagate_to_loaders: bool = (source)

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.

Undocumented

def _apply_to_parent(self, parent: Load): (source)

apply this :class:`_orm._AbstractLoad` object as a sub-option o a :class:`_orm.Load` object. Implementation is provided by subclasses.

def _clone_for_bind_strategy(self, attrs: Optional[Tuple[_AttrType, ...]], strategy: Optional[_StrategyKey], wildcard_key: Optional[_WildcardKeyType], opts: Optional[_OptsType] = None, attr_group: Optional[_AttrGroupType] = None, propagate_to_loaders: bool = True, reconcile_to_other: Optional[bool] = None) -> Self: (source)
@overload
def _coerce_strat(self, strategy: _StrategySpec) -> _StrategyKey:
@overload
def _coerce_strat(self, strategy: Literal[None]):
(source)

Undocumented

def _process(self, compile_state: ORMCompileState, mapper_entities: Sequence[_MapperEntity], raiseerr: bool): (source)
@_generative
def _set_class_strategy(self, strategy: _StrategySpec, opts: _OptsType) -> Self: (source)

Undocumented

@_generative
def _set_column_strategy(self, attrs: Tuple[_AttrType, ...], strategy: Optional[_StrategySpec], opts: Optional[_OptsType] = None) -> Self: (source)

Undocumented

@_generative
def _set_generic_strategy(self, attrs: Tuple[_AttrType, ...], strategy: _StrategySpec, _reconcile_to_other: Optional[bool] = None) -> Self: (source)

Undocumented

@_generative
def _set_relationship_strategy(self, attr: _AttrType, strategy: Optional[_StrategySpec], propagate_to_loaders: bool = True, opts: Optional[_OptsType] = None, _reconcile_to_other: Optional[bool] = None) -> Self: (source)

Undocumented