简体   繁体   中英

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 

Item.objects.annotate(
    
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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