Flask SQLAlchemy query, specify column names

Viewed 205020

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?

10 Answers

You can use Query.values, Query.values

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

I usually use this snippet:

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

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

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

An alternate syntax to fetch entity with specific columns:

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