Flask SQLAlchemy query, specify column names
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Realization
--
Chapters
00:00 Question
00:35 Accepted answer (Score 318)
01:05 Answer 2 (Score 103)
01:25 Answer 3 (Score 77)
01:41 Answer 4 (Score 11)
02:22 Thank you
--
Full question
https://stackoverflow.com/questions/1153...
Accepted answer links:
[documentation]: http://docs.sqlalchemy.org/en/latest/orm...
[deferreds]: http://docs.sqlalchemy.org/en/latest/orm...
Answer 3 links:
[load_only]: https://docs.sqlalchemy.org/en/latest/or...
Answer 4 links:
[Sesssion.query_property]: http://docs.sqlalchemy.org/en/rel_0_7/or...
[add_columns()]: http://docs.sqlalchemy.org/en/rel_0_7/or...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sqlalchemy #flasksqlalchemy
#avk47
ACCEPTED ANSWER
Score 332
You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.
ANSWER 2
Score 110
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
ANSWER 3
Score 85
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
ANSWER 4
Score 11
You can use Model.query, because the Model (or usually its base class, especially in cases where declarative extension is used) is assigned Sesssion.query_property. In this case the Model.query is equivalent to Session.query(Model).
I am not aware of the way to modify the columns returned by the query (except by adding more using add_columns()).
So your best shot is to use the Session.query(Model.col1, Model.col2, ...) (as already shown by Salil).