问题
I need to construct a query where the selected columns in the result are changing. How can I add columns to the result progressively similar to .filter
:
query = session.query(User).filter(name == 'Hansen').filter(country == 'Spain')
Thanks!
回答1:
The sqlalchemy Query class has an add_columns method that can be used for this.
cols = ['col1', 'col2', 'col3', 'col4']
q = session.query()
for c in cols:
q = q.add_columns(getattr(MyTable, c))
res = q.all()
As the name suggests, the method will accept more than one column expression.
q.add_columns(*list_of_columns)
Query.add_entity would be used to add an orm entity, such as a model class, to the query.
q = session.query()
q = q.add_entity(MyTable)
# Fetch objects, not just columns
list_of_objs = q.all()
来源:https://stackoverflow.com/questions/57873787/how-to-create-a-query-and-add-columns-to-select-sequentially