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

标签 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()中

最佳答案

使用 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))

关于Django 1.6 如何同时正确注释 Count() 和 Sum()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22199375/

相关文章:

python - 在 Django 中,如何只打印错误而不打印 key ?

python - Django - 组管理模型中的更改字段

python - 如何在 Django 休息框架响应中获取过滤的 Django ORM 查询结果

Django 管理员 : Prefill data when clicking the add-another button next to a ForeignKey dropdown

python - 检查 Django 中是否存在用户名

python - 如何根据 django 中的屏幕大小将模型列表分配为行和列?

python - Firefox 没有收到 django csrf_token

python - 带有高亮模板标签的安全过滤器 django-haystack

Python Django 防止多对多字段中的重复

django - 在 Django-Registration 中通过注册保存配置文件