Flask SQLAlchemy query, specify column names Flask SQLAlchemy query, specify column names python python

Flask SQLAlchemy query, specify column names


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.


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'))


You can use load_only function:

from sqlalchemy.orm import load_onlyfields = ['name', 'addr', 'phone', 'url']companies = session.query(SomeModel).options(load_only(*fields)).all()