Query Results as KeyedTuple?

18 views
Skip to first unread message

Laura Wilby

unread,
Dec 30, 2019, 6:18:16 PM12/30/19
to sqlalchemy
I would like to be able to do something like this ... 

>>>  test = session.query(T1, T2).first()
>>>  test

( 't1':  <T1 object>,  't2':  <T2 object>)

I've been looking in the documentation for a way to accomplish this or something similar, but haven't been able to find anything. 

Thanks so much for taking a look at my question!


Mike Bayer

unread,
Dec 30, 2019, 9:11:47 PM12/30/19
to noreply-spamdigest via sqlalchemy
if you run session.query(T1, T2), the result you'd get back is currently the KeyedTuple object.   it's a tuple, which you can refer to it by key, however, if T1 and T2 are mapped classes, the names of the keys would be "T1" and "T2", which are the names of the mapped classes.    

If these were column expressions, you'd use label() to change their names, e.g. some_col.label("my_column"), however for ORM mapped classes, right now you can use aliased() to achieve this:

from sqlalchemy.orm import aliased

t1 = aliased(T1, name="t1")
t2 = aliased(T2, name="t2")
session.query(t1, t2).filter(t1.foo == 'bar').filter (etc)

those names will be applied to the named tuple result you get back.  In the next major release, version 1.4, the KeyedTuple class is likely being replaced with a new object called "Row" but the user-facing behavior will be the same.






--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Laura Wilby

unread,
Dec 31, 2019, 1:13:19 PM12/31/19
to sqlalchemy
Thank-you Mike, that is perfect. I now feel silly I didn't realize that it wasn't a regular tuple, but also very happy that it is the KeyedTuple :)
To unsubscribe from this group and stop receiving emails from it, send an email to sqlal...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages