Likes機能を反映するためPost
にManyToMany関係を持つモデルがあります。User
さらにPost
、各投稿は既存のコメントにすることができるため、それ自体との ForeignKey 関係がありますPost
(1 つの深さレベルのみが強制されます - ディスカッション ツリーはありません)。
現在、最も活発な議論を得るために集計を使用しようとしています。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"
vs.
COUNT(T7."user_id") AS "clc"
最初の SQL リターンのような結果を達成するために集計を使用するid
代わりに、またはより賢い方法でdjango を強制的にカウントする方法はありますか?user_id