[Fixed]-Calculating score by counting and subtracting foreign key instances in Django

1👍

from django.db.models import Count  

positive_karma = Summary.objects.filter(author=self.user).aggregate(pos_count=Count('users_rated_positive'))['pos_count']

negative_karma = Summary.objects.filter(author=self.user).aggregate(neg_count=Count('users_rated_negative'))['neg_count']

aggregate returns a dict so the actual value must be retrieved by the key

You would use annotate if you wanted to get the count of pos/neg ratings for every user.

👤zxzak

Leave a comment