Django 1.6如何正确地同时注释Count()和Sum()?

时间:2014-03-05 13:37:13

标签: django

简单描述:

#for each q in Question , q.votes is correct
Question.objects.annotate(votes=Sum('vote__value')) 
#add a Count annotate, q.answers is correct, while q.votes not.
Question.objects.annotate(votes=Sum('vote__value', distinct=True),answers=Count('answer', distinct=True),)

enter image description here

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

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.

Click Here如果需要,下载测试项目代码。测试函数在raw.tests.test()

2 个答案:

答案 0 :(得分:1)

使用Django 1.11,您可以使用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))

答案 1 :(得分:0)

感谢anuragal。他提醒我。我想到了额外

qs3 = Question.objects.extra(
    select={
    'answers': 'SELECT COUNT(*) FROM raw_answer WHERE raw_answer.question_id = raw_question.id',
    'votes':'SELECT SUM(value) FROM raw_vote WHERE raw_vote.question_id = raw_question.id',
    },

这没关系。