Django 1.6如何同时正确注释Count()和Sum()? [英] Django 1.6 how to correctly annotate Count() and Sum() at the same time?

查看:43
本文介绍了Django 1.6如何同时正确注释Count()和Sum()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单描述:

#for Question中的每个q,q.votes是正确的Question.objects.annotate(votes = Sum('vote__value'))#添加计数注释,q.answers是正确的,而q.votes不正确.Question.objects.annotate(votes = Sum('vote__value',distinct = True),answers = Count('answer',distinct = True),)

如果我想同时注释Count()和Sum(),如何?因此,我可以做类似的事情:

If I want to annotate Count() and Sum() at the same time, How? Thus I can do something like:

qs = Question.objects.annotate(votes=Sum('vote__value', distinct=True),answers=Count('answer', distinct=True),)
for q in qs:
    #do something with q.votes and q.answers in a template
    #this will be convenient.

单击此处,以根据需要下载测试项目代码.测试功能在raw.tests.test()

Click Here to download the test project code if needed.Test function is in raw.tests.test()

推荐答案

在Django 1.11中,您可以使用

With Django 1.11 you can use Subquery()

votes = Vote.objects.filter(question=OuterRef('pk').order_by().values('question')
sum_votes = votes.annotate(s=Sum('value')).values('s')

answers = Answer.objects.filter(question=OuterRef('pk').order_by().values('question')
count_answers = answers.annotate(c=Count('*')).values('c')

qs = Question.objects.annotate(votes=Subquery(sum_votes),
                               answers=Subquery(count_answers))

这篇关于Django 1.6如何同时正确注释Count()和Sum()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆