首页 > 解决方案 > 使用聚合查找记录计数的差异

问题描述

我的任务是使用聚合/注释将此代码写入一个查询。

我尝试使用计数和东西,但我不知道这是如何工作的

upvotes = UserVote.objects.filter(blog=self, vote_type='U').count()
downvotes = UserVote.objects.filter(blog=self, vote_type='D').count()
return upvotes - downvotes

标签: pythondjango

解决方案


无论如何,我用这个做到了:

return Blog.objects.aggregate(total_votes=(Count('post_votes', filter=Q(post_votes__vote_type='U') & Q(post_votes__blog=self)) - Count('post_votes', filter=Q(post_votes__vote_type='D') & Q(post_votes__blog=self))))


推荐阅读