【问题标题】:Count number of SQLAlchemy relationships inside a filter计算过滤器中 SQLAlchemy 关系的数量
【发布时间】:2019-12-15 08:45:22
【问题描述】:

我一直在尝试用谷歌搜索,但我只是想出如何检索计数而不是按它过滤。我找到的最接近的结果是this answer,但我正在构建没有会话的查询,因此使用object_session 会引发UnmappedInstanceError

给定ParentChild 模型,通过Parent.children 连接,我如何查询哪些父母有一定数量的孩子?

我试过session.query(Parent).filter(func.count(Parent.children)>1),但它抱怨滥用count 函数。

当我为搜索函数递归构建查询时,查询实际上是由几十个过滤器组成的,所以如果可能的话,我希望它保留在一个过滤器中。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    我认为这样的事情可能会起作用(根本没有经过测试)

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

    【讨论】:

    • 谢谢,虽然我想查询哪些父母有一定数量的孩子,而不是查询单亲(如果我错了,请纠正我,但上面的查询不一样效果为len(parent.children) > 5?)。我相信我需要相当于WHERE (SELECT count(*) from Children where Children.parent_id == Parent.row_id) > 5,如果我打印出我的查询,SQLAlchemy 只会做WHERE count(Children.parent_id == Parent.row_id) > 5。我不太擅长 SQL,但我认为问题可能归结于此。我尝试加入Children 并测试了一些group_by 但没有运气。
    • 没关系,在输入该评论后想通了 :)
    【解决方案2】:

    在将生成的 SQL 与实际需要的 SQL 进行比较后,我注意到它需要一个嵌套的 select 语句,可以使用 sqlalchemy.select 来完成。

    而不是这个:

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

    正确的语法是这样的:

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

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2021-04-23
      • 2012-01-23
      相关资源
      最近更新 更多