class documentation

class LoaderCriteriaOption(CriteriaOption):

View In Hierarchy

Add additional WHERE criteria to the load for all occurrences of a particular entity.

_orm.LoaderCriteriaOption is invoked using the _orm.with_loader_criteria function; see that function for details.

New in version 1.4.
Method __init__ Add additional WHERE criteria to the load for all occurrences of a particular entity.
Method ​_all​_mappers Undocumented
Method ​_resolve​_where​_criteria Undocumented
Method ​_should​_include Undocumented
Method get​_global​_criteria update additional entity criteria options in the given attributes dictionary.
Method process​_compile​_state Apply a modification to a given .CompileState.
Method process​_compile​_state​_replaced​_entities Apply a modification to a given .CompileState, given entities that were replaced by with_only_columns() or with_entities().
Class Variable ​_traverse​_internals Undocumented
Instance Variable deferred​_where​_criteria Undocumented
Instance Variable entity Undocumented
Instance Variable include​_aliases Undocumented
Instance 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.
Instance Variable root​_entity Undocumented
Instance Variable where​_criteria Undocumented

Inherited from CriteriaOption:

Class Variable ​_is​_criteria​_option Undocumented

Inherited from CompileStateOption (via CriteriaOption):

Class Variable ​_is​_compile​_state Undocumented

Inherited from HasCacheKey (via CriteriaOption, CompileStateOption):

Class Variable inherit​_cache Indicate if this .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 __slots__ 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 CriteriaOption, CompileStateOption):

Class Variable __slots__ Undocumented
Class Variable ​_is​_legacy​_option Undocumented
Class Variable ​_is​_strategy​_option Undocumented

Inherited from ExecutableOption (via CriteriaOption, CompileStateOption, ORMOption):

Method ​_clone Create a shallow copy of this ExecutableOption.
Class Variable __visit​_name__ Undocumented
Class Variable ​_is​_has​_cache​_key Undocumented

Inherited from HasCopyInternals (via CriteriaOption, CompileStateOption, ORMOption, ExecutableOption):

Method ​_copy​_internals Reassign internal elements to be clones of themselves.
def __init__(self, entity_or_base, where_criteria, loader_only=False, include_aliases=False, propagate_to_loaders=True, track_closure_variables=True):

Add additional WHERE criteria to the load for all occurrences of a particular entity.

New in version 1.4.

The _orm.with_loader_criteria option is intended to add limiting criteria to a particular kind of entity in a query, globally, meaning it will apply to the entity as it appears in the SELECT query as well as within any subqueries, join conditions, and relationship loads, including both eager and lazy loaders, without the need for it to be specified in any particular part of the query. The rendering logic uses the same system used by single table inheritance to ensure a certain discriminator is applied to a table.

E.g., using :term:`2.0-style` queries, we can limit the way the User.addresses collection is loaded, regardless of the kind of loading used:

from sqlalchemy.orm import with_loader_criteria

stmt = select(User).options(
    selectinload(User.addresses),
    with_loader_criteria(Address, Address.email_address != 'foo'))
)

Above, the "selectinload" for User.addresses will apply the given filtering criteria to the WHERE clause.

Another example, where the filtering will be applied to the ON clause of the join, in this example using :term:`1.x style` queries:

q = session.query(User).outerjoin(User.addresses).options(
    with_loader_criteria(Address, Address.email_address != 'foo'))
)

The primary purpose of _orm.with_loader_criteria is to use it in the _orm.SessionEvents.do_orm_execute event handler to ensure that all occurrences of a particular entity are filtered in a certain way, such as filtering for access control roles. It also can be used to apply criteria to relationship loads. In the example below, we can apply a certain set of rules to all queries emitted by a particular _orm.Session:

session = Session(bind=engine)

@event.listens_for("do_orm_execute", session)
def _add_filtering_criteria(execute_state):

    if (
        execute_state.is_select
        and not execute_state.is_column_load
        and not execute_state.is_relationship_load
    ):
        execute_state.statement = execute_state.statement.options(
            with_loader_criteria(
                SecurityRole,
                lambda cls: cls.role.in_(['some_role']),
                include_aliases=True
            )
        )

In the above example, the _orm.SessionEvents.do_orm_execute event will intercept all queries emitted using the _orm.Session. For those queries which are SELECT statements and are not attribute or relationship loads a custom _orm.with_loader_criteria option is added to the query. The _orm.with_loader_criteria option will be used in the given statement and will also be automatically propagated to all relationship loads that descend from this query.

The criteria argument given is a lambda that accepts a cls argument. The given class will expand to include all mapped subclass and need not itself be a mapped class.

Tip

When using _orm.with_loader_criteria option in conjunction with the _orm.contains_eager loader option, it's important to note that _orm.with_loader_criteria only affects the part of the query that determines what SQL is rendered in terms of the WHERE and FROM clauses. The _orm.contains_eager option does not affect the rendering of the SELECT statement outside of the columns clause, so does not have any interaction with the _orm.with_loader_criteria option. However, the way things "work" is that _orm.contains_eager is meant to be used with a query that is already selecting from the additional entities in some way, where _orm.with_loader_criteria can apply it's additional criteria.

In the example below, assuming a mapping relationship as A -> A.bs -> B, the given _orm.with_loader_criteria option will affect the way in which the JOIN is rendered:

stmt = select(A).join(A.bs).options(
    contains_eager(A.bs),
    with_loader_criteria(B, B.flag == 1)
)

Above, the given _orm.with_loader_criteria option will affect the ON clause of the JOIN that is specified by .join(A.bs), so is applied as expected. The _orm.contains_eager option has the effect that columns from B are added to the columns clause:

SELECT
    b.id, b.a_id, b.data, b.flag,
    a.id AS id_1,
    a.data AS data_1
FROM a JOIN b ON a.id = b.a_id AND b.flag = :flag_1

The use of the _orm.contains_eager option within the above statement has no effect on the behavior of the _orm.with_loader_criteria option. If the _orm.contains_eager option were omitted, the SQL would be the same as regards the FROM and WHERE clauses, where _orm.with_loader_criteria continues to add its criteria to the ON clause of the JOIN. The addition of _orm.contains_eager only affects the columns clause, in that additional columns against b are added which are then consumed by the ORM to produce B instances.

Warning

The use of a lambda inside of the call to _orm.with_loader_criteria is only invoked once per unique class. Custom functions should not be invoked within this lambda. See :ref:`engine_lambda_caching` for an overview of the "lambda SQL" feature, which is for advanced use only.

See Also

:ref:`examples_session_orm_events` - includes examples of using _orm.with_loader_criteria.

:ref:`do_orm_execute_global_criteria` - basic example on how to combine _orm.with_loader_criteria with the _orm.SessionEvents.do_orm_execute event.

Parameters
entity​_or​_basea mapped class, or a class that is a super class of a particular set of mapped classes, to which the rule will apply.
where​_criteriaa Core SQL expression that applies limiting criteria. This may also be a "lambda:" or Python function that accepts a target class as an argument, when the given class is a base with many different mapped subclasses.
loader​_onlyUndocumented
include​_aliasesif True, apply the rule to _orm.aliased constructs as well.
propagate​_to​_loadersdefaults to True, apply to relationship loaders such as lazy loaders.
track​_closure​_variables

when False, closure variables inside of a lambda expression will not be used as part of any cache key. This allows more complex expressions to be used inside of a lambda expression but requires that the lambda ensures it returns the identical SQL every time given a particular class.

New in version 1.4.0b2.
def _all_mappers(self):

Undocumented

def _resolve_where_criteria(self, ext_info):

Undocumented

def _should_include(self, compile_state):

Undocumented

def get_global_criteria(self, attributes):
update additional entity criteria options in the given attributes dictionary.
def process_compile_state(self, compile_state):
Apply a modification to a given .CompileState.
def process_compile_state_replaced_entities(self, compile_state, mapper_entities):

Apply a modification to a given .CompileState, given entities that were replaced by with_only_columns() or with_entities().

New in version 1.4.19.
_traverse_internals =

Undocumented

deferred_where_criteria: bool =

Undocumented

entity =

Undocumented

include_aliases =

Undocumented

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.
root_entity =

Undocumented

where_criteria =

Undocumented