Skip to content

Commit b7a8ea1

Browse files
zzzeekGerrit Code Review
authored andcommitted
Merge "mention adapt on names" into main
2 parents 7194b5b + b4068fd commit b7a8ea1

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

doc/build/orm/queryguide/select.rst

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ Selecting Entities from Subqueries
365365
The :func:`_orm.aliased` construct discussed in the previous section
366366
can be used with any :class:`_sql.Subquery` construct that comes from a
367367
method such as :meth:`_sql.Select.subquery` to link ORM entities to the
368-
columns returned by that subquery; there must be a **column correspondence**
368+
columns returned by that subquery; by default, there must be a **column correspondence**
369369
relationship between the columns delivered by the subquery and the columns
370370
to which the entity is mapped, meaning, the subquery needs to be ultimately
371371
derived from those entities, such as in the example below::
@@ -387,6 +387,25 @@ derived from those entities, such as in the example below::
387387
User(id=4, name='squidward', fullname='Squidward Tentacles')
388388
User(id=5, name='ehkrabs', fullname='Eugene H. Krabs')
389389

390+
Alternatively, an aliased subquery can be matched to the entity based on name
391+
by applying the :paramref:`_orm.aliased.adapt_on_names` parameter::
392+
393+
>>> from sqlalchemy import literal
394+
>>> inner_stmt = select(
395+
... literal(14).label("id"),
396+
... literal("made up name").label("name"),
397+
... literal("made up fullname").label("fullname"),
398+
... )
399+
>>> subq = inner_stmt.subquery()
400+
>>> aliased_user = aliased(User, subq, adapt_on_names=True)
401+
>>> stmt = select(aliased_user)
402+
>>> for user_obj in session.execute(stmt).scalars():
403+
... print(user_obj)
404+
{execsql}SELECT anon_1.id, anon_1.name, anon_1.fullname
405+
FROM (SELECT ? AS id, ? AS name, ? AS fullname) AS anon_1
406+
[generated in ...] (14, 'made up name', 'made up fullname')
407+
{stop}User(id=14, name='made up name', fullname='made up fullname')
408+
390409
.. seealso::
391410

392411
:ref:`tutorial_subqueries_orm_aliased` - in the :ref:`unified_tutorial`

0 commit comments

Comments
 (0)