Dynamically query a subset of columns in sqlalchemy

Assume that only two columns are required from the table (name and identifier). I would encode 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 looks ugly. Is there a better recommended way?

+3
source share
1 answer

You can use select () :

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

Hope this helps.

+3
source

All Articles