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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You can use Query.values, Query.values
session.query(SomeModel).values('id', 'user')
is the same as
for alias, we can use .label()
An example here:
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
You can use
Model.query
, because theModel
(or usually its base class, especially in cases where declarative extension is used) is assignedSesssion.query_property
. In this case theModel.query
is equivalent toSession.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).You can use the
with_entities()
method to restrict which columns you'd like to return in the result. (documentation)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.
You can use load_only function: