我有一个Post
具有多对多关系的模型User
来反映喜欢功能。此外Post
,ForeignKey 与自身有关系,因为每个帖子都可以是对现有的评论Post
(仅强制一个深度级别 - 没有讨论树)。
现在我正在尝试使用聚合来获得最活跃的讨论。我想计算每一个的分数,Post
它是它的喜欢、评论和评论的喜欢的总和。
以下 SQL 完美运行:
SELECT "posting_post"."id",
"posting_post"."title",
"posting_post"."content",
"posting_post"."pub_date",
"posting_post"."parent_id",
"posting_post"."user_id",
COUNT(DISTINCT T4."id") AS "cc",
COUNT(DISTINCT "posting_post_likes"."id") AS "lc",
COUNT(DISTINCT T7."id") AS "clc"
FROM "posting_post"
LEFT OUTER JOIN "posting_post" T4 ON ("posting_post"."id" = T4."parent_id")
LEFT OUTER JOIN "posting_post_likes" ON ("posting_post"."id" = "posting_post_likes"."post_id")
LEFT OUTER JOIN "posting_post_likes" T7 ON (T4."id" = T7."post_id")
WHERE "posting_post"."parent_id" IS NULL
GROUP BY "posting_post"."id",
"posting_post"."title",
"posting_post"."content",
"posting_post"."pub_date",
"posting_post"."parent_id",
"posting_post"."user_id"
ORDER BY cc+lc+clc DESC LIMIT 10
当我尝试使用聚合时:
Post.objects.filter(parent=None).annotate(clc=models.Count('comments__likes', discinct=True), cc=models.Count('comments', distinct=True), lc=models.Count('likes', distinct=True))[:10]
生成以下 SQL:
SELECT "posting_post"."id",
"posting_post"."title",
"posting_post"."content",
"posting_post"."pub_date",
"posting_post"."parent_id",
"posting_post"."user_id",
COUNT(DISTINCT T4."id") AS "cc",
COUNT(DISTINCT "posting_post_likes"."user_id") AS "lc",
COUNT(T7."user_id") AS "clc"
FROM "posting_post"
LEFT OUTER JOIN "posting_post" T4 ON ("posting_post"."id" = T4."parent_id")
LEFT OUTER JOIN "posting_post_likes" ON ("posting_post"."id" = "posting_post_likes"."post_id")
LEFT OUTER JOIN "posting_post_likes" T7 ON (T4."id" = T7."post_id")
WHERE "posting_post"."parent_id" IS NULL
GROUP BY "posting_post"."id",
"posting_post"."title",
"posting_post"."content",
"posting_post"."pub_date",
"posting_post"."parent_id",
"posting_post"."user_id"
ORDER BY "posting_post"."pub_date" DESC LIMIT 10
这不像我预期的那样工作。请注意主要区别:
COUNT(DISTINCT T7."id") AS "clc"
与。
COUNT(T7."user_id") AS "clc"
是否有某种方法可以强制 django 进行计数id
,而不是user_id
使用聚合来实现第一个 SQL 返回等结果的更聪明的方法?