PonyORM:如何摆脱 "subquery uses ungrouped column"?

PonyORM: how to get rid of "subquery uses ungrouped column"?

请假设 this data model。这是我真正拥有的简化模型,但所有重要领域都在那里。数据库:Postgres。我想计算这些模型的一些统计数据,我偶然发现了这个问题:

c = Customer.select().random(1)[0]  # example
query = left_join(
        (
            p,
            count(i.order.customer == c),
            count((b.is_used == True) for b in i.bonuses),
            count(i)
        ) for p in Product
        for i in p.order_items)

现在尝试显示结果(实际上我需要对聚合进行更多过滤)

query.show()

产生这个:

ProgrammingError: subquery uses ungrouped column "i.id" from outer query
LINE 4:     WHERE "i"."id" = "b"."order_item"

我该怎么做才能纠正这个问题?

结果 SQL 看起来像这样:

SELECT "p"."id", COUNT(case when "order"."customer" = ? then 1 else null end), (
    SELECT COUNT(DISTINCT "b"."is_used" = 1)
    FROM "Bonus" "b"
    WHERE "i"."id" = "b"."order_item"
    ), COUNT(DISTINCT "i"."id")
FROM "Product" "p"
  LEFT JOIN "OrderItem" "i"
    ON "p"."id" = "i"."product"
  LEFT JOIN "Order" "order"
    ON "i"."order" = "order"."id"
GROUP BY "p"."id"

编辑: 我的真实模型是为适应 Django 使用的数据库而制作的,所以我在每个 class 中都有 _table_,在所有外键中都有 column=something_id。但除此之外,一切看起来都很好,我可以轻松地进行任何更简单的查询。

编辑2: Here's the gist with my test data.

看来我需要将代码改写成这种形式:

query = left_join(
    (
        p,
        count(i.order.customer == c),
        count(b.is_used == True),
        count(i)
    ) for p in Product
    for i in p.order_items
    for b in i.bonuses)