Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy ORM: modify the columns returned from a query

If I've got an SQLAlchemy ORM query:

admin_users = Session.query(User).filter_by(is_admin=True)

Is it possible to modify the columns returned by that query?

For example, so that I could select only the User.id column, and use that in a sub query:

admin_email_addresses = Session.query(EmailAddress)\
    .filter(EmailAddress.user_id.in_(admin_users.select_columns(User.id))

Note: the .values() method will not work, as it executes the query and returns an iterable of results (so, ex, EmailAddress.user_id.in_(admin_users.values(User.id)) will perform two queries, not one).

I know that I could modify the first query to be Session.query(User.id), but I'm specifically wondering how I could modify the columns returned by a query.

like image 472
David Wolever Avatar asked May 20 '12 21:05

David Wolever


1 Answers

I feel your pain on the values() thing. In 0.6.5 I added with_entities() which is just like values() except doesn't iterate:

q = q.with_entities(User.id)
like image 146
zzzeek Avatar answered Oct 04 '22 17:10

zzzeek