[英]Annotate sum of vote scores to an item in Django
I have a situation, need to count sum of vote scores and annotate that to an item queryset.我有一种情况,需要计算投票分数的总和并将其注释到项目查询集。
model:模型:
class Vote(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name="votes")
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="votes")
score = models.IntegerField()
I tried different variations of this but keep failing:我尝试了不同的变体,但一直失败:
all_votes = Vote.objects.filter(item=OuterRef('pk'))
Item.objects.annotate(total_score=Sum(Subquery(all_votes.values("score"))))
I get this back all the time:我总是得到这个:
ProgrammingError: more than one row returned by a subquery used as an expression
You don't need a subquery here.这里不需要子查询。 You can annotate with:您可以使用以下注释进行注释:
from django.db.models import Sum
Item.objects.annotate(
total_score=Sum('votes__score')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.