Flask SQLAlchemy 查询,指定列名 [英] Flask SQLAlchemy query, specify column names
问题描述
如何使用模型在查询中指定所需的列(默认情况下它会选择所有列)?我知道如何使用 sqlalchmey 会话执行此操作:session.query(self.col1)
,但是我如何使用模型执行此操作?我不能做 SomeModel.query()
.有办法吗?
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?
推荐答案
您可以使用 with_entities()
方法来限制您希望在结果中返回哪些列.(文档)>
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.
这篇关于Flask SQLAlchemy 查询,指定列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!