Please assume this data model. This is a simplified model of what I really have here but all important fields are there. Database: Postgres. I want to calculate some stats on those models and I stumbled upon this problem:
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)
Now trying to show results (in reality I have some more filtering on the aggregations to do)
query.show()
yields this:
ProgrammingError: subquery uses ungrouped column "i.id" from outer query
LINE 4: WHERE "i"."id" = "b"."order_item"
What can I do to correct this?
Resulting SQL looks like this:
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"
EDIT:
My real models are made to fit a db used by Django, so I have _table_
in each class and column=something_id
in all foreign keys. But aside that everything looks OK to the point I can make any simpler query with ease.
It appears that I needed to rephrase the code to this form:
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)