]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
mention adapt on names
authorMike Bayer <mike_mp@zzzcomputing.com>
Thu, 18 Dec 2025 14:19:12 +0000 (09:19 -0500)
committerMike Bayer <mike_mp@zzzcomputing.com>
Thu, 18 Dec 2025 14:19:54 +0000 (09:19 -0500)
make sure we include that column correspondence is not
the only way to do this

Change-Id: I4fa78f2e79585c1796c3dc169f88c849d604f668
(cherry picked from commit b4068fd0227b980bb9e6340befd649d4d261c2c7)

doc/build/orm/queryguide/select.rst

index a8b273a62dcca2b77495c4267609a5d201055122..4895c43682ded0e0a6b92eea039fee631f3f086e 100644 (file)
@@ -362,7 +362,7 @@ Selecting Entities from Subqueries
 The :func:`_orm.aliased` construct discussed in the previous section
 can be used with any :class:`_sql.Subquery` construct that comes from a
 method such as :meth:`_sql.Select.subquery` to link ORM entities to the
-columns returned by that subquery; there must be a **column correspondence**
+columns returned by that subquery; by default, there must be a **column correspondence**
 relationship between the columns delivered by the subquery and the columns
 to which the entity is mapped, meaning, the subquery needs to be ultimately
 derived from those entities, such as in the example below::
@@ -384,6 +384,25 @@ derived from those entities, such as in the example below::
     User(id=4, name='squidward', fullname='Squidward Tentacles')
     User(id=5, name='ehkrabs', fullname='Eugene H. Krabs')
 
+Alternatively, an aliased subquery can be matched to the entity based on name
+by applying the :paramref:`_orm.aliased.adapt_on_names` parameter::
+
+    >>> from sqlalchemy import literal
+    >>> inner_stmt = select(
+    ...     literal(14).label("id"),
+    ...     literal("made up name").label("name"),
+    ...     literal("made up fullname").label("fullname"),
+    ... )
+    >>> subq = inner_stmt.subquery()
+    >>> aliased_user = aliased(User, subq, adapt_on_names=True)
+    >>> stmt = select(aliased_user)
+    >>> for user_obj in session.execute(stmt).scalars():
+    ...     print(user_obj)
+    {execsql}SELECT anon_1.id, anon_1.name, anon_1.fullname
+    FROM (SELECT ? AS id, ? AS name, ? AS fullname) AS anon_1
+    [generated in ...] (14, 'made up name', 'made up fullname')
+    {stop}User(id=14, name='made up name', fullname='made up fullname')
+
 .. seealso::
 
     :ref:`tutorial_subqueries_orm_aliased` - in the :ref:`unified_tutorial`