繁体   English   中英

将投票分数总和注释到 Django 中的项目

[英]Annotate sum of vote scores to an item in Django

我有一种情况,需要计算投票分数的总和并将其注释到项目查询集。

模型:

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()

我尝试了不同的变体,但一直失败:

all_votes = Vote.objects.filter(item=OuterRef('pk'))
Item.objects.annotate(total_score=Sum(Subquery(all_votes.values("score"))))

我总是得到这个:

ProgrammingError: more than one row returned by a subquery used as an expression

这里不需要子查询。 您可以使用以下注释进行注释:

from django.db.models import Sum

Item.objects.annotate(
    total_score=Sum('votes__score')
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM