Flask SQLAlchemy query, specify column names

PythonSqlalchemyFlask Sqlalchemy

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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](http://docs.sqlalchemy.org/en/latest/orm/loading_columns.html#deferred "SQLAlchemy deferred column loading") useful. They allow you to return the full object but restrict the columns that come over the wire.

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

You can use Query.values, Query.values

session.query(SomeModel).values('id', 'user')

Solution 6 - Python

I usually use this snippet:

fields = ["col1", "col2", ...]\
session.query(map(lambda x: getattr(SomeModel.c, x), fields))

Solution 7 - Python

result = ModalName.query.add_columns(ModelName.colname, ModelName.colname)

Solution 8 - Python

As session.query(SomeModel.col1) returns an array of tuples like this [('value_1',),('value_2',)] if you want t cast the result to a plain array you can do it by using one of the following statements:

values = [value[0] for value in session.query(SomeModel.col1)]
values = [model.col1 for model in session.query(SomeModel).options(load_only('col1'))]

Result:

 ['value_1', 'value_2']

Solution 9 - Python

An alternate syntax to fetch entity with specific columns:

any_query.with_entities(Entity).options(load_only(Entity.col))

Solution 10 - Python

An example here:

movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()

I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.

Take a look here: Select, Insert, Delete in Flask-SQLAlchemy

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew ScraggView Question on Stackoverflow
Solution 1 - PythonDavid McKeoneView Answer on Stackoverflow
Solution 2 - PythonSalilView Answer on Stackoverflow
Solution 3 - PythonVlad BezdenView Answer on Stackoverflow
Solution 4 - PythonvanView Answer on Stackoverflow
Solution 5 - PythongaozhidfView Answer on Stackoverflow
Solution 6 - PythonCarlos RCView Answer on Stackoverflow
Solution 7 - PythonBasurp PatilView Answer on Stackoverflow
Solution 8 - PythonfabriciorissettoView Answer on Stackoverflow
Solution 9 - Pythonuser2599052View Answer on Stackoverflow
Solution 10 - PythonhappygoatView Answer on Stackoverflow