9

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?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. it works. Is this equivalent to query(User.id, User.name) or are there any differences?
add from sqlalchemy.sql import select
Not sure why I receive Textual column expression 'name' should be explicitly declared with text('name'), or use column('name') for more specificity"
I don't think this answer works any more. The OP's solution is the correct solution according to latest update from SQLAlchemy: Changed in version 1.4: The select() construct now accepts column arguments positionally, as select(*args). The previous style of select() accepting a list of column elements is now deprecated. See select(), case() now accept positional expressions. docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql
in 2023 you can use columns = ["id", "name"], then cols = [getattr(MyModel, col) for col in columns], then query = select(*cols)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.