Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically query a subset of columns in sqlalchemy

Assume only two columns(name and id) are needed from a table. I would code something like below:

session.query(User.id, User.name).all()

But if the column names are dynamic,

def get_data(table, columns):
    return session.query(*(getattr(table, column) for column in columns)).all()

But the above one looks ugly. Is there a better recommended way?

like image 963
balki Avatar asked Jan 13 '14 22:01

balki


1 Answers

You can get use of select():

from sqlalchemy.sql import select

columns = ['id', 'name']
print(session.query(select(from_obj=User, columns=columns)).all())

Hope that helps.

like image 194
alecxe Avatar answered Oct 18 '22 22:10

alecxe