简体   繁体   English

计算过滤器中SQLAlchemy关系的数量

[英]Count number of SQLAlchemy relationships inside a filter

I've been trying to google this but I'm only really coming up with how to retrieve the count rather than filter by it. 我一直在尝试用谷歌搜索,但我只是想出了如何检索计数而不是按其筛选。 The closest result I found was this answer , but I'm constructing the query without a session so using object_session raises UnmappedInstanceError . 我找到的最接近结果是这个答案 ,但是我在没有会话的情况下构造了查询,因此使用object_session会引发UnmappedInstanceError

Given Parent and Child models, connected by Parent.children , how could I query which parents have a certain amount of children? 给定由Parent.children连接的ParentChild模型,如何查询哪些父母有一定数量的孩子?

I've tried session.query(Parent).filter(func.count(Parent.children)>1) , but it complains about misuse of the count function. 我已经尝试了session.query(Parent).filter(func.count(Parent.children)>1) ,但是它抱怨count功能的滥用。

As I'm building the query recursively for a search function, the query is actually built up of dozens of filters, so if at all possible I'd like this to remain in a single filter. 在为搜索功能递归构建查询时,查询实际上由数十个过滤器组成,因此,如果可能的话,我希望将其保留在单个过滤器中。

I think something like this might work (not at all tested) 我认为类似这样的方法可能会起作用(根本没有经过测试)

session.query(func.count(Children.parent_id))\
    .group_by(Children.parent_id)\
    .filter(func.count(Children.parent_id) > 5)

After comparing the generated SQL with what is actually needed, I noticed it needed a nested select statement, which can be done with sqlalchemy.select . 将生成的SQL与实际需要的进行比较之后,我注意到它需要一个嵌套的select语句,可以使用sqlalchemy.select来完成。

Instead of this: 代替这个:

session.query(Parent).filter(func.count(Parent.children)>1)

The correct syntax is this: 正确的语法是这样的:

subsearch = select([func.count(Parent.children)]).where(Parent.row_id==Child.parent_id).as_scalar()
session.query(Parent).filter(subsearch>1)

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

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