我有以下表达式:
Product.objects.annotate(views_total=models.Sum('stats__views'))
正确连接Product和Stats表并聚合每个product.id的stats.views字段:
SELECT
"product"."id", "product"."name", SUM("stats"."views") AS "views_total"
FROM
"product" LEFT OUTER JOIN "stats" ON ("product"."id" = "stats"."product_id")
GROUP BY "product"."id";
我正在尝试弄清楚如何在已加入的统计信息表中添加条件,该条件对应于此类查询:
SELECT
"product"."id", "product"."name", SUM("stats"."views") AS "views_total"
FROM
"product" LEFT OUTER JOIN "stats" ON ("product"."id" = "stats"."product_id") AND ("stats"."condition" > 100)
GROUP BY "product"."id";
我试过了:
Product.objects.annotate(views_total=models.Sum('stats__views')).filter(stats__condition__gt = 100)
但是这导致内部连接不能产生所需的结果:
SELECT
"product"."id", "product"."name", SUM("stats"."views") AS "views_total"
FROM
"product" LEFT OUTER JOIN "stats" ON ("product"."id" = "stats"."product_id")
INNER JOIN
"stats" T3 ON ("product"."id" = T3."product_id")
WHERE (T3."condition" > 100)
GROUP BY "product"."id";