注释中的多个连接

时间:2014-06-11 10:38:08

标签: python django django-models django-orm django-aggregation

我有Post模型与User具有ManyToMany关系以反映喜欢功能。此外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

当我尝试使用aggreagtions时:

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返回的结果一样?

0 个答案:

没有答案