Fix Python – Flask SQLAlchemy query, specify column names

Question

Asked By – Matthew Scragg

How do I specify the column that I want in my query using a model (it selects all columns by default)? I know how to do this with the sqlalchmey session: session.query(self.col1), but how do I do it with with models? I can’t do SomeModel.query(). Is there a way?

Now we will see solution for issue: Flask SQLAlchemy query, specify column names


Answer

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.

This question is answered By – David McKeone

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0