簡體   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