【问题标题】:Is it possible to narrow down the generated query in SQLAlchemy if it was created via query_property?如果它是通过 query_property 创建的,是否可以缩小 SQLAlchemy 中生成的查询的范围?
【发布时间】:2010-01-24 20:57:33
【问题描述】:

我还有一个关于 SQLAlchemy 的小问题。

如果我在我的 SQLAlchemy Table 类中添加了 query_property [1] 字段,是否可以缩小 SELECTed 字段的范围?

这就是我的意思。

假设我的班级Comments 有这个:

class Comments:
    query = Session.query_property()
    ...

如果我执行以下操作:

>>> print Session.query(Comment)                      

然后 SQLAlchemy 生成以下查询,其中包括我的 comments 表中的所有列:

SELECT comments.comment_id AS comments_comment_id,
       comments.comment    AS comments_comment
       ... more columns ...
FROM comments

但我想缩小此查询范围并仅选择(比方说)comment 字段,如下所示:

>>> print Session.query(Comment.comment)   
SELECT comments.comment AS comments_comment 
FROM comments

是否可以通过Comment.query 构造来做到这一点?

我尝试了以下方法,但没有成功:

>>> print Comment.query(Comment.comment)                
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'Query' object is not callable

请帮我提个建议。

谢谢,博达·赛多。

[1]http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.scoping.ScopedSession.query_property

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    尝试使用query.values(Comment.comment)。注意它返回的是生成器,而不是修改后的查询,所以这个方法应该在应用所有过滤器后最后调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多