简体   繁体   English

如何在SQLAlchemy中按关系数量选择模型,然后按相同数量排序?

[英]How do I select a model in SQLAlchemy by the number of relationships it has, and then order by the same number?

So I can easily select by the value of a relationship's field, but I can't for the life of me figure out how to select and order by the number of relationships. 因此,我可以轻松地通过关系字段的值进行选择,但是我一生都无法通过关系数量来确定如何选择和排序。 Specifically, what I want to do is select all users with at least one post, and then order by the users with the most posts. 具体来说,我想做的是选择所有拥有至少一个帖子的用户,然后按拥有最多帖子的用户进行排序。 I want to do this without storing an extra field in the database as a post count, or selecting all of them and sorting them manually. 我想做到这一点而无需在数据库中存储额外的字段作为发布计数,或者选择所有这些字段并手动对其进行排序。

Something like 就像是

User.query.filter(len(User.posts.all()) > 0).all()

would be ideal for example, though this doesn't seem to work. 例如,这将是理想的,尽管这似乎不起作用。

Any ideas? 有任何想法吗?

use having() 使用Have()

from sqlalchemy import func

session.query(User).\
        join(User.posts).\
        group_by(User).\
        having(func.count(Post.id) > 0).\
        order_by(func.count(Post.id).desc())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM