【发布时间】:2014-03-05 13:37:13
【问题描述】:
简单说明:
#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),)
如果我想同时注释 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()中
【问题讨论】:
-
您将如何为此编写单个 SQL 查询?
-
@anuragal 我不熟悉 SQL..你能举个例子吗?
-
distinct=True应该从Sum注释中删除。 QuerySet 实际上应该可以与两个注释一起正常工作。
标签: django