python - 使用聚合查找记录计数的差异
问题描述
我的任务是使用聚合/注释将此代码写入一个查询。
我尝试使用计数和东西,但我不知道这是如何工作的
upvotes = UserVote.objects.filter(blog=self, vote_type='U').count()
downvotes = UserVote.objects.filter(blog=self, vote_type='D').count()
return upvotes - downvotes
解决方案
无论如何,我用这个做到了:
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))))
推荐阅读
- python-3.x - 递归问题中使用不同参数多次调用的函数
- reactjs - Mongoose - 检查数据库是否存在
- python - 为什么在这里设置相等中断?
- c# - 生成的绑定删除泛型
- database - 如何撤销用户对 DB2 中数据库元数据表的访问权限
- java - 如何以编程方式获取 jar 中的所有 *.json 文件?
- php - 如何使 php 将所有子链接重定向到我的索引页?
- excel - Excel:我想根据中断发生的时间为中断分配一个小时的成本
- python - 在多索引熊猫数据框上选择范围
- ruby-on-rails - 缺少 nokogiri gemspec 时出现 Rails 控制台错误,但 nokogiri 没有 gemspec