ORM API Features for Querying

ORM Loader Options

ローダーオプションは、 Select オブジェクトや同様のSQL構文の Select.options() メソッドに渡されると、列と関係指向の属性の両方のロードに影響するオブジェクトです。ローダーオプションの大部分は Load 階層から派生しています。ローダーオプションの使用方法の完全な概要については、以下のリンクされたセクションを参照してください。

See also

ORM Execution Options

ORMレベルの実行オプションは、 Session.execute.execution_options パラメータ( Session.execute()Session.scalars() のような Session メソッドで受け付けられる辞書引数)を使用するか、 Executable.execution_options() メソッドを使用して呼び出される文に直接関連付けることで、文の実行に関連付けることができるキーワードオプションです。 execute.execution_options() メソッドは、任意のキーワード引数として受け付けます。

ORMレベルのオプションは、 Connection.execution_options() で説明されているコアレベルの実行オプションとは異なります。以下で説明するORMオプションは、コアレベルのメソッド Connection.execution_options() または Engine.execution_options() と**互換性がない**ことに注意してください。このレベルでは、 Engine または Connection が使用中の Session に関連付けられていても、これらのオプションは無視されます。

このセクションでは、例として Executable.execution_options() メソッドスタイルについて説明します。

Populate Existing

populate_existing 実行オプションは、ロードされたすべての行に対して、 Session 内の対応するインスタンスが完全に更新されることを保証します。つまり、オブジェクト内の既存のデータ(保留中の変更を含む)を消去し、結果からロードされたデータで置き換えます。

使用例は次のようになります。:

>>> stmt = select(User).execution_options(populate_existing=True)
>>> result = session.execute(stmt)
SELECT user_account.id, user_account.name, user_account.fullname FROM user_account ...

通常、ORMオブジェクトは一度だけロードされ、後続の結果行の主キーと一致する場合、その行はオブジェクトに適用されません。これは、オブジェクトの保留中のフラッシュされていない変更を保持するとともに、すでに存在するデータを更新するオーバーヘッドと複雑さを回避するためです。 Session は、高度に分離されたトランザクションのデフォルトの作業モデルを想定しており、ローカルな変更が行われていないトランザクション内でデータが変更されると予想される場合には、これらのユースケースはこのメソッドのような明示的なステップを使用して処理されます。

populate_existing を使用すると、クエリに一致するオブジェクトの任意のセットを更新できます。また、関係ローダのオプションを制御することもできます。たとえば、インスタンスを更新すると同時に、関連するオブジェクトのセットも更新します。

stmt = (
    select(User)
    .where(User.name.in_(names))
    .execution_options(populate_existing=True)
    .options(selectinload(User.addresses))
)
# will refresh all matching User objects as well as the related
# Address objects
users = session.execute(stmt).scalars().all()

populate_existing のもう1つの使用例は、クエリごとに属性のロード方法を変更できるさまざまな属性ロード機能のサポートです。これが適用されるオプションは次のとおりです。>

  • 更新する属性を選択するための load_only() オプション

populate_existing 実行オプションは、 1.x style ORMクエリの Query.populate_existing() メソッドと等価です。

Autoflush

このオプションを False として渡すと、 Session は”autoflush”ステップを呼び出さなくなります。これは Session.no_autoflush コンテキストマネージャを使ってautoflushを無効にするのと同じです:

>>> stmt = select(User).execution_options(autoflush=False)
>>> session.execute(stmt)
SELECT user_account.id, user_account.name, user_account.fullname FROM user_account ...

このオプションは、ORMを有効にした UpdateDelete クエリでも動作します。

autoflush 実行オプションは、 1.x style ORMクエリの Query.autoflush() メソッドと等価です。

See also

Flushing

Fetching Large Result Sets with Yield Per

yield_per 実行オプションは整数値で、 Result が一度に限られた数の行やORMオブジェクトだけをバッファリングしてから、クライアントがデータを利用できるようにします。

通常、ORMは すべての 行を即座に取得し、それぞれに対してORMオブジェクトを構築し、それらのオブジェクトを単一のバッファにまとめてから、返される行のソースとしてこのバッファを Result オブジェクトに渡します。この動作の理論的根拠は、結合されたイーガーローディング、結果の一元化、結果セット内のすべてのオブジェクトが取得されたときに一貫した状態を維持するIDマップに依存する結果処理ロジックの一般的なケースなどの機能に対して正しい動作を可能にすることです。

yield_per オプションの目的は、この動作を変更して、ユーザが上記のパターンが適用されないと判断した場合に、ORM結果セットが非常に大きな結果セット(例えば、10K行以上)の反復のために最適化されるようにすることです。 yield_per が使用されると、ORMは代わりにORM結果をサブコレクションにバッチ化し、 Result オブジェクトが反復されるときに各サブコレクションから個別に行を生成するので、Pythonインタプリタは時間がかかり、過度のメモリ使用につながる非常に大きなメモリ領域を宣言する必要がありません。このオプションは、データベースカーソルの使用方法と、ORMが Result に渡される行とオブジェクトを構築する方法の両方に影響します。

Tip

上記のことから、 Result は反復可能な方法で、つまり for row in result のような反復を使って、あるいは Result.fetchmany()Result.partitions() のような部分的な行のメソッドを使って、消費されなければならないということになります。 Result.all() を呼び出すと、 yield_per を使う目的が無効になります。

yield_per を使用することは、実行オプション Connection.execution_options.stream_resultsResult.yield_per() の両方を使用することと同じです。 Connection.execution_options.stream_results は、サーバ側のカーソルがサポートされている場合にバックエンドで使用されるように選択します。 Result.yield_per() メソッドは、返された Result オブジェクトに対して使用されます。 Result オブジェクトは、取得される行の固定サイズと、一度に構築されるORMオブジェクトの数の制限を設定します。

Tip

Using Server Side Cursors (a.k.a. stream results) で詳細に説明されているように、Coreの実行オプションとしても yield_per が利用できるようになりました。このセクションでは、ORM Session での実行オプションとしての yield_per の使用について詳しく説明します。このオプションは、両方のコンテキストで可能な限り同じように動作します。

ORMで使用する場合は、与えられた文の Executable.execution_options() メソッドか、 Session.execute()Session.execute.execution_options パラメータ、または Session.scalars() のような他の同様の Session メソッドに渡すことで、 yield_per を確立する必要があります。ORMオブジェクトを取得するための典型的な使用法を以下に示します。:

>>> stmt = select(User).execution_options(yield_per=10)
>>> for user_obj in session.scalars(stmt):
...     print(user_obj)
SELECT user_account.id, user_account.name, user_account.fullname FROM user_account [...] ()
User(id=1, name='spongebob', fullname='Spongebob Squarepants') User(id=2, name='sandy', fullname='Sandy Cheeks') ... >>> # ... rows continue ...

上のコードは以下の例と同じです。この例では Connection.execution_options.stream_resultsConnection.execution_options.max_row_buffer のコアレベルの実行オプションを、 ResultResult.yield_per() メソッドと組み合わせて使用しています:

# equivalent code
>>> stmt = select(User).execution_options(stream_results=True, max_row_buffer=10)
>>> for user_obj in session.scalars(stmt).yield_per(10):
...     print(user_obj)
SELECT user_account.id, user_account.name, user_account.fullname FROM user_account [...] ()
User(id=1, name='spongebob', fullname='Spongebob Squarepants') User(id=2, name='sandy', fullname='Sandy Cheeks') ... >>> # ... rows continue ...

yield_per は、グループ化されたパーティションの行を繰り返す Result.partitions() メソッドと組み合わせてもよく使われます。各パーティションのサイズは、以下の例のように yield_per に渡される整数値にデフォルトで設定されます。:

>>> stmt = select(User).execution_options(yield_per=10)
>>> for partition in session.scalars(stmt).partitions():
...     for user_obj in partition:
...         print(user_obj)
SELECT user_account.id, user_account.name, user_account.fullname FROM user_account [...] ()
User(id=1, name='spongebob', fullname='Spongebob Squarepants') User(id=2, name='sandy', fullname='Sandy Cheeks') ... >>> # ... rows continue ...

コレクションを使用する場合、 yield_per 実行オプションは、 “subquery”eager loading loadingまたは “joined”eager loading と互換性がありません 。データベースドライバが複数の独立したカーソルをサポートしている場合、 “selectin”eager loading と互換性がある可能性があります。

さらに、 yield_per 実行オプションは Result.unique() メソッドと互換性がありません。このメソッドは全ての行の完全なIDを保存することに依存しているので、任意の数の行を扱う yield_per を使用する目的を必然的に損なうことになります。

Changed in version 1.4.6: Result.unique() フィルタを使用する Result オブジェクトからORM行が取得され、同時に実行オプション yield_per が使用される場合、例外が発生します。

レガシーの Query オブジェクトを 1.x style ORMで使用する場合、 Query.yield_per() メソッドは、実行オプションの yield_per と同じ結果になります。

Identity Token

Deep Alchemy

このオプションは高度な機能で、主に Horizontal Sharding 拡張と一緒に使用することを意図しています。異なる”シャード”やパーティションから同一の主キーを持つオブジェクトをロードする典型的なケースでは、まずシャードごとに個別の Session オブジェクトを使用することを検討してください。

“identity token”は、新しくロードされたオブジェクトの identity key 内に関連付けられる任意の値です。この要素は、何よりもまず、行ごとの”シャーディング”を実行する拡張をサポートするために存在します。この拡張では、オブジェクトは、重複する主キー値を持つ特定のデータベーステーブルの任意の数のレプリカからロードできます。”identity token”の主なコンシューマは Horizontal Sharding 拡張で、特定のデータベーステーブルの複数の”シャード”間でオブジェクトを永続化するための一般的なフレームワークを提供します。

identity_token 実行オプションをクエリごとに使用して、このトークンに直接影響を与えることができます。これを直接使用すると、同じ主キーとソーステーブルを持つが、「ID」が異なるオブジェクトの複数のインスタンスを Session に設定できます。

そのような例の1つは、 Translation of Schema Names 機能を使用して、異なるスキーマの同じ名前のテーブルから来たオブジェクトで Session を作成することです。この機能は、クエリのスコープ内でのスキーマの選択に影響を与える可能性があります。次のようなマッピングが与えられます。:

from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column

class Base(DeclarativeBase):
    pass

class MyTable(Base):
    __tablename__ = "my_table"

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

上記のクラスのデフォルトの”スキーマ”名は None です。これは、スキーマ修飾がSQL文に書き込まれないことを意味します。しかし、 Connection.execution_options.schema_translate_map を使用して、 None を別のスキーマにマッピングすると、 MyTable のインスタンスを2つの異なるスキーマに配置できます。

engine = create_engine(
    "postgresql+psycopg://scott:tiger@localhost/test",
)

with Session(
    engine.execution_options(schema_translate_map={None: "test_schema"})
) as sess:
    sess.add(MyTable(name="this is schema one"))
    sess.commit()

with Session(
    engine.execution_options(schema_translate_map={None: "test_schema_2"})
) as sess:
    sess.add(MyTable(name="this is schema two"))
    sess.commit()

上記の2つのブロックは、毎回異なるスキーマ変換マップにリンクされた Session オブジェクトを作成し、 MyTable のインスタンスは test_schema.my_tabletest_schema_2.my_table の両方に保存されます。

上記の Session オブジェクトは独立しています。1つのトランザクションで両方のオブジェクトを永続化したい場合は、 Horizontal Sharding 拡張を使用する必要があります。

ただし、1つのセッションでこれらのオブジェクトのクエリーを実行する例を次に示します。:

with Session(engine) as sess:
    obj1 = sess.scalar(
        select(MyTable)
        .where(MyTable.id == 1)
        .execution_options(
            schema_translate_map={None: "test_schema"},
            identity_token="test_schema",
        )
    )
    obj2 = sess.scalar(
        select(MyTable)
        .where(MyTable.id == 1)
        .execution_options(
            schema_translate_map={None: "test_schema_2"},
            identity_token="test_schema_2",
        )
    )

Horizontal Sharding 拡張を使用すると、上記のロジックが自動的に実行されます。

New in version 2.0.0rc1: - added the identity_token ORM level execution option.

See also

Horizontal Sharding - ORM Examples セクションにあります。完全なシャーディングAPIを使用した上記のユースケースのデモについては、スクリプト separate_schema_translates.py を参照してください。

Inspecting entities and columns from ORM-enabled SELECT and DML statements

select() 構文と、 insert()update() および delete() 構文(SQLAlchemy 1.4.33以降のDML構文の場合)はすべて、これらの文が作成された対象のエンティティと、結果セットで返される列とデータ型を検査する機能をサポートしています。

Select オブジェクトの場合、この情報は Select.column_descriptions 属性から取得できます。この属性は、従来の Query.column_descriptions 属性と同じように動作します。返される書式は辞書のリストです:

>>> from pprint import pprint
>>> user_alias = aliased(User, name="user2")
>>> stmt = select(User, User.id, user_alias)
>>> pprint(stmt.column_descriptions)
[{'aliased': False,
  'entity': <class 'User'>,
  'expr': <class 'User'>,
  'name': 'User',
  'type': <class 'User'>},
 {'aliased': False,
  'entity': <class 'User'>,
  'expr': <....InstrumentedAttribute object at ...>,
  'name': 'id',
  'type': Integer()},
 {'aliased': True,
  'entity': <AliasedClass ...; User>,
  'expr': <AliasedClass ...; User>,
  'name': 'user2',
  'type': <class 'User'>}]

Select.column_descriptions が普通の TableColumn オブジェクトのような非ORMオブジェクトと共に使用される時、エントリは全ての場合に返される個々の列についての基本情報を含んでいます:

>>> stmt = select(user_table, address_table.c.id)
>>> pprint(stmt.column_descriptions)
[{'expr': Column('id', Integer(), table=<user_account>, primary_key=True, nullable=False),
  'name': 'id',
  'type': Integer()},
 {'expr': Column('name', String(), table=<user_account>, nullable=False),
  'name': 'name',
  'type': String()},
 {'expr': Column('fullname', String(), table=<user_account>),
  'name': 'fullname',
  'type': String()},
 {'expr': Column('id', Integer(), table=<address>, primary_key=True, nullable=False),
  'name': 'id_1',
  'type': Integer()}]

Changed in version 1.4.33: Select.column_descriptions 属性は、ORM対応でない Select に対して使用された場合に値を返すようになりました。以前は、これは NotImplementedError を発生させていました。

insert(),:func:.update および delete() 構文には、2つの独立した属性があります。1つは UpdateBase.entity_description で、DML構文が影響するプライマリORMエンティティとデータベーステーブルに関する情報を返します:

>>> from sqlalchemy import update
>>> stmt = update(User).values(name="somename").returning(User.id)
>>> pprint(stmt.entity_description)
{'entity': <class 'User'>,
 'expr': <class 'User'>,
 'name': 'User',
 'table': Table('user_account', ...),
 'type': <class 'User'>}

Tip

The UpdateBase.entity_description includes an entry "table" which is actually the table to be inserted, updated or deleted by the statement, which is not always the same as the SQL “selectable” to which the class may be mapped. For example, in a joined-table inheritance scenario, "table" will refer to the local table for the given entity.

Tip

UpdateBase.entity_description にはエントリ "table" が含まれています。これは実際には文によって 挿入、更新、削除されるテーブル ですが、クラスがマップされる可能性のある”選択可能な”SQLと必ずしも同じでは ありません 。例えば、結合テーブルの継承のシナリオでは、 "table" は与えられたエンティティのローカルテーブルを参照します。

もう1つは UpdateBase.returning_column_descriptions で、RETURNINGコレクションに存在する列に関する情報を、 Select.column_descriptions とほぼ同じ方法で提供します:

>>> pprint(stmt.returning_column_descriptions)
[{'aliased': False,
  'entity': <class 'User'>,
  'expr': <sqlalchemy.orm.attributes.InstrumentedAttribute ...>,
  'name': 'id',
  'type': Integer()}]

New in version 1.4.33: UpdateBase.entity_description および UpdateBase.returning_column_descriptions 属性が追加されました。

Additional ORM API Constructs

Object Name Description

aliased(element[, alias, name, flat, ...])

Produce an alias of the given element, usually an AliasedClass instance.

AliasedClass

Represents an “aliased” form of a mapped class for usage with Query.

AliasedInsp

Provide an inspection interface for an AliasedClass object.

Bundle

A grouping of SQL expressions that are returned by a Query under one namespace.

join(left, right[, onclause, isouter, ...])

Produce an inner join between left and right clauses.

outerjoin(left, right[, onclause, full])

Produce a left outer join between left and right clauses.

with_loader_criteria(entity_or_base, where_criteria[, loader_only, include_aliases, ...])

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

with_parent(instance, prop[, from_entity])

Create filtering criterion that relates this query’s primary entity to the given related instance, using established relationship() configuration.

function sqlalchemy.orm.aliased(element: _EntityType[_O] | FromClause, alias: FromClause | None = None, name: str | None = None, flat: bool = False, adapt_on_names: bool = False) AliasedClass[_O] | FromClause | AliasedType[_O]

Produce an alias of the given element, usually an AliasedClass instance.

E.g.:

my_alias = aliased(MyClass)

stmt = select(MyClass, my_alias).filter(MyClass.id > my_alias.id)
result = session.execute(stmt)

The aliased() function is used to create an ad-hoc mapping of a mapped class to a new selectable. By default, a selectable is generated from the normally mapped selectable (typically a Table ) using the FromClause.alias() method. However, aliased() can also be used to link the class to a new select() statement. Also, the with_polymorphic() function is a variant of aliased() that is intended to specify a so-called “polymorphic selectable”, that corresponds to the union of several joined-inheritance subclasses at once.

For convenience, the aliased() function also accepts plain FromClause constructs, such as a Table or select() construct. In those cases, the FromClause.alias() method is called on the object and the new Alias object returned. The returned Alias is not ORM-mapped in this case.

Parameters:
  • element – element to be aliased. Is normally a mapped class, but for convenience can also be a FromClause element.

  • alias – Optional selectable unit to map the element to. This is usually used to link the object to a subquery, and should be an aliased select construct as one would produce from the Query.subquery() method or the Select.subquery() or Select.alias() methods of the select() construct.

  • name – optional string name to use for the alias, if not specified by the alias parameter. The name, among other things, forms the attribute name that will be accessible via tuples returned by a Query object. Not supported when creating aliases of Join objects.

  • flat

    Boolean, will be passed through to the FromClause.alias() call so that aliases of 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.

    When aliased.flat is combined with aliased.name, the resulting joins will alias individual tables using a naming scheme similar to <prefix>_<tablename>. This naming scheme is for visibility / debugging purposes only and the specific scheme is subject to change without notice.

    New in version 2.0.32: added support for combining aliased.name with aliased.flat. Previously, this would raise NotImplementedError.

  • adapt_on_names

    if True, more liberal “matching” will be used when mapping the mapped columns of the ORM entity to those of the given selectable - a name-based match will be performed if the given selectable doesn’t otherwise have a column that corresponds to one on the entity. The use case for this is when associating an entity with some derived selectable such as one that uses aggregate functions:

    class UnitPrice(Base):
        __tablename__ = 'unit_price'
        ...
        unit_id = Column(Integer)
        price = Column(Numeric)
    
    aggregated_unit_price = Session.query(
                                func.sum(UnitPrice.price).label('price')
                            ).group_by(UnitPrice.unit_id).subquery()
    
    aggregated_unit_price = aliased(UnitPrice,
                alias=aggregated_unit_price, adapt_on_names=True)

    Above, functions on aggregated_unit_price which refer to .price will return the func.sum(UnitPrice.price).label('price') column, as it is matched on the name “price”. Ordinarily, the “price” function wouldn’t have any “column correspondence” to the actual UnitPrice.price column as it is not a proxy of the original.

class sqlalchemy.orm.util.AliasedClass

Represents an “aliased” form of a mapped class for usage with Query.

The ORM equivalent of a alias() construct, this object mimics the mapped class using a __getattr__ scheme and maintains a reference to a real Alias object.

A primary purpose of AliasedClass is to serve as an alternate within a SQL statement generated by the ORM, such that an existing mapped entity can be used in multiple contexts. A simple example:

# find all pairs of users with the same name
user_alias = aliased(User)
session.query(User, user_alias).\
                join((user_alias, User.id > user_alias.id)).\
                filter(User.name == user_alias.name)

AliasedClass is also capable of mapping an existing mapped class to an entirely new selectable, provided this selectable is column- compatible with the existing mapped selectable, and it can also be configured in a mapping as the target of a relationship(). See the links below for examples.

The AliasedClass object is constructed typically using the aliased() function. It also is produced with additional configuration when using the with_polymorphic() function.

The resulting object is an instance of AliasedClass. This object implements an attribute scheme which produces the same attribute and method interface as the original mapped class, allowing AliasedClass to be compatible with any attribute technique which works on the original class, including hybrid attributes (see Hybrid Attributes).

The AliasedClass can be inspected for its underlying Mapper, aliased selectable, and other information using inspect():

from sqlalchemy import inspect
my_alias = aliased(MyClass)
insp = inspect(my_alias)

The resulting inspection object is an instance of AliasedInsp.

Class signature

class sqlalchemy.orm.AliasedClass (sqlalchemy.inspection.Inspectable, sqlalchemy.orm.ORMColumnsClauseRole)

class sqlalchemy.orm.util.AliasedInsp

Provide an inspection interface for an AliasedClass object.

The AliasedInsp object is returned given an AliasedClass using the inspect() function:

from sqlalchemy import inspect
from sqlalchemy.orm import aliased

my_alias = aliased(MyMappedClass)
insp = inspect(my_alias)

Attributes on AliasedInsp include:

  • entity - the AliasedClass represented.

  • mapper - the Mapper mapping the underlying class.

  • selectable - the Alias construct which ultimately represents an aliased Table or Select construct.

  • name - the name of the alias. Also is used as the attribute name when returned in a result tuple from Query.

  • with_polymorphic_mappers - collection of Mapper objects indicating all those mappers expressed in the select construct for the AliasedClass.

  • polymorphic_on - an alternate column or SQL expression which will be used as the “discriminator” for a polymorphic load.

Class signature

class sqlalchemy.orm.AliasedInsp (sqlalchemy.orm.ORMEntityColumnsClauseRole, sqlalchemy.orm.ORMFromClauseRole, sqlalchemy.sql.cache_key.HasCacheKey, sqlalchemy.orm.base.InspectionAttr, sqlalchemy.util.langhelpers.MemoizedSlots, sqlalchemy.inspection.Inspectable, typing.Generic)

class sqlalchemy.orm.Bundle

A grouping of SQL expressions that are returned by a Query under one namespace.

The Bundle essentially allows nesting of the tuple-based results returned by a column-oriented Query object. It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without involving ORM identity-mapped classes.

Class signature

class sqlalchemy.orm.Bundle (sqlalchemy.orm.ORMColumnsClauseRole, sqlalchemy.sql.annotation.SupportsCloneAnnotations, sqlalchemy.sql.cache_key.MemoizedHasCacheKey, sqlalchemy.inspection.Inspectable, sqlalchemy.orm.base.InspectionAttr)

method sqlalchemy.orm.Bundle.__init__(name: str, *exprs: _ColumnExpressionArgument[Any], **kw: Any)

Construct a new Bundle.

e.g.:

bn = Bundle("mybundle", MyClass.x, MyClass.y)

for row in session.query(bn).filter(
        bn.c.x == 5).filter(bn.c.y == 4):
    print(row.mybundle.x, row.mybundle.y)
Parameters:
  • name – name of the bundle.

  • *exprs – columns or SQL expressions comprising the bundle.

  • single_entity=False – if True, rows for this Bundle can be returned as a “single entity” outside of any enclosing tuple in the same manner as a mapped entity.

attribute sqlalchemy.orm.Bundle.c: ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]

An alias for Bundle.columns.

attribute sqlalchemy.orm.Bundle.columns: ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]

A namespace of SQL expressions referred to by this Bundle.

e.g.:

bn = Bundle("mybundle", MyClass.x, MyClass.y)

q = sess.query(bn).filter(bn.c.x == 5)

Nesting of bundles is also supported:

b1 = Bundle("b1",
        Bundle('b2', MyClass.a, MyClass.b),
        Bundle('b3', MyClass.x, MyClass.y)
    )

q = sess.query(b1).filter(
    b1.c.b2.c.a == 5).filter(b1.c.b3.c.y == 9)

See also

Bundle.c

method sqlalchemy.orm.Bundle.create_row_processor(query: Select[Any], procs: Sequence[Callable[[Row[Any]], Any]], labels: Sequence[str]) Callable[[Row[Any]], Any]

Produce the “row processing” function for this Bundle.

May be overridden by subclasses to provide custom behaviors when results are fetched. The method is passed the statement object and a set of “row processor” functions at query execution time; these processor functions when given a result row will return the individual attribute value, which can then be adapted into any kind of return data structure.

The example below illustrates replacing the usual Row return structure with a straight Python dictionary:

from sqlalchemy.orm import Bundle

class DictBundle(Bundle):
    def create_row_processor(self, query, procs, labels):
        'Override create_row_processor to return values as
        dictionaries'

        def proc(row):
            return dict(
                zip(labels, (proc(row) for proc in procs))
            )
        return proc

A result from the above Bundle will return dictionary values:

bn = DictBundle('mybundle', MyClass.data1, MyClass.data2)
for row in session.execute(select(bn)).where(bn.c.data1 == 'd1'):
    print(row.mybundle['data1'], row.mybundle['data2'])
attribute sqlalchemy.orm.Bundle.is_aliased_class = False

True if this object is an instance of AliasedClass.

attribute sqlalchemy.orm.Bundle.is_bundle = True

True if this object is an instance of Bundle.

attribute sqlalchemy.orm.Bundle.is_clause_element = False

True if this object is an instance of ClauseElement.

attribute sqlalchemy.orm.Bundle.is_mapper = False

True if this object is an instance of Mapper.

method sqlalchemy.orm.Bundle.label(name)

Provide a copy of this Bundle passing a new label.

attribute sqlalchemy.orm.Bundle.single_entity = False

If True, queries for a single Bundle will be returned as a single entity, rather than an element within a keyed tuple.

function sqlalchemy.orm.with_loader_criteria(entity_or_base: _EntityType[Any], where_criteria: _ColumnExpressionArgument[bool] | Callable[[Any], _ColumnExpressionArgument[bool]], loader_only: bool = False, include_aliases: bool = False, propagate_to_loaders: bool = True, track_closure_variables: bool = True) LoaderCriteriaOption

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

New in version 1.4.

The 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 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 1.x style queries:

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

The primary purpose of with_loader_criteria() is to use it in the 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 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 SessionEvents.do_orm_execute() event will intercept all queries emitted using the Session. For those queries which are SELECT statements and are not attribute or relationship loads a custom with_loader_criteria() option is added to the query. The 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 with_loader_criteria() option in conjunction with the contains_eager() loader option, it’s important to note that 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 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 with_loader_criteria() option. However, the way things “work” is that contains_eager() is meant to be used with a query that is already selecting from the additional entities in some way, where with_loader_criteria() can apply it’s additional criteria.

In the example below, assuming a mapping relationship as A -> A.bs -> B, the given 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 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 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 contains_eager() option within the above statement has no effect on the behavior of the with_loader_criteria() option. If the contains_eager() option were omitted, the SQL would be the same as regards the FROM and WHERE clauses, where with_loader_criteria() continues to add its criteria to the ON clause of the JOIN. The addition of 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 with_loader_criteria() is only invoked once per unique class. Custom functions should not be invoked within this lambda. See Using Lambdas to add significant speed gains to statement production for an overview of the “lambda SQL” feature, which is for advanced use only.

Parameters:
  • entity_or_base – a mapped class, or a class that is a super class of a particular set of mapped classes, to which the rule will apply.

  • where_criteria

    a 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.

    Note

    To support pickling, use a module-level Python function to produce the SQL expression instead of a lambda or a fixed SQL expression, which tend to not be picklable.

  • include_aliases – if True, apply the rule to aliased() constructs as well.

  • propagate_to_loaders

    defaults to True, apply to relationship loaders such as lazy loaders. This indicates that the option object itself including SQL expression is carried along with each loaded instance. Set to False to prevent the object from being assigned to individual instances.

    See also

    ORM Query Events - includes examples of using with_loader_criteria().

    Adding global WHERE / ON criteria - basic example on how to combine with_loader_criteria() with the SessionEvents.do_orm_execute() event.

  • 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.

function sqlalchemy.orm.join(left: _FromClauseArgument, right: _FromClauseArgument, onclause: _OnClauseArgument | None = None, isouter: bool = False, full: bool = False) _ORMJoin

Produce an inner join between left and right clauses.

join() is an extension to the core join interface provided by join(), where the left and right selectable may be not only core selectable objects such as Table, but also mapped classes or AliasedClass instances. The “on” clause can be a SQL expression or an ORM mapped attribute referencing a configured relationship().

join() is not commonly needed in modern usage, as its functionality is encapsulated within that of the Select.join() and Query.join() methods. which feature a significant amount of automation beyond join() by itself. Explicit use of join() with ORM-enabled SELECT statements involves use of the Select.select_from() method, as in:

from sqlalchemy.orm import join
stmt = select(User).\
    select_from(join(User, Address, User.addresses)).\
    filter(Address.email_address=='foo@bar.com')

In modern SQLAlchemy the above join can be written more succinctly as:

stmt = select(User).\
        join(User.addresses).\
        filter(Address.email_address=='foo@bar.com')

Warning

using join() directly may not work properly with modern ORM options such as with_loader_criteria(). It is strongly recommended to use the idiomatic join patterns provided by methods such as Select.join() and Select.join_from() when creating ORM joins.

See also

Joins - in the ORM Querying Guide for background on idiomatic ORM join patterns

function sqlalchemy.orm.outerjoin(left: _FromClauseArgument, right: _FromClauseArgument, onclause: _OnClauseArgument | None = None, full: bool = False) _ORMJoin

Produce a left outer join between left and right clauses.

This is the “outer join” version of the join() function, featuring the same behavior except that an OUTER JOIN is generated. See that function’s documentation for other usage details.

function sqlalchemy.orm.with_parent(instance: object, prop: attributes.QueryableAttribute[Any], from_entity: _EntityType[Any] | None = None) ColumnElement[bool]

Create filtering criterion that relates this query’s primary entity to the given related instance, using established relationship() configuration.

E.g.:

stmt = select(Address).where(with_parent(some_user, User.addresses))

The SQL rendered is the same as that rendered when a lazy loader would fire off from the given parent on that attribute, meaning that the appropriate state is taken from the parent object in Python without the need to render joins to the parent table in the rendered statement.

The given property may also make use of PropComparator.of_type() to indicate the left side of the criteria:

a1 = aliased(Address)
a2 = aliased(Address)
stmt = select(a1, a2).where(
    with_parent(u1, User.addresses.of_type(a2))
)

The above use is equivalent to using the from_entity() argument:

a1 = aliased(Address)
a2 = aliased(Address)
stmt = select(a1, a2).where(
    with_parent(u1, User.addresses, from_entity=a2)
)
Parameters:
  • instance – An instance which has some relationship().

  • property – Class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship.

  • from_entity

    Entity in which to consider as the left side. This defaults to the “zero” entity of the Query itself.

    New in version 1.2.