Flask SQLAlchemy查询,指定列名 [英] Flask SQLAlchemy query, specify column names

查看:831
本文介绍了Flask SQLAlchemy查询,指定列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用模型在查询中指定所需的列(默认情况下会选择所有列)?我知道如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆