How to create a query and add columns to select sequentially?

本小妞迷上赌 提交于 2020-01-30 12:14:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!