django
Can't query the sum of values using aggregators
I want to sum the values of all existing rows grouping by another field. Here's my model structure: class Answer(models.Model): person = models.ForeignKey(Person) points = models.PositiveIntegerField(default=100) correct = models.BooleanField(default=False) class Person(models.Model): # irrelevant model fields Sample dataset: Person | Points ------ | ------ 4 | 90 3 | 50 3 | 100 2 | 100 2 | 90 Here's my query: Answer.objects.values('person').filter(correct=True).annotate(points_person=Sum('points')) And the result (you can see that all the person values are separated): [{'person': 4, 'points_person': 90}, {'person': 3, 'points_person': 50}, {'person': 3, 'points_person': 100}, {'person': 2, 'points_person': 100}, {'person': 2, 'points_person': 90}] But what I want (sum of points by each person): [{'person': 4, 'points_person': 90}, {'person': 3, 'points_person': 150}, {'person': 2, 'points_person': 190}] Is there any way to achieve this using only queryset filtering? Thanks!
Turns out I had to do the inverse filtering, by the Person's and not the Answers, like so: Person.objects.filter(answer__correct=True).annotate(points=Sum('answer__points')) Now I get the total summed points for each person correctly.
Related Links
Cookies causing django crash when upgrading from 1.3 to 1.4
getting distinct values from inputs that share the same name
Celery with Django and MongoDB (mongoengine)
How to delete a lot of objects from database
How to use image field in Django unit test
Django and radio buttons
django i18n translation not working on nginx but works on runserver
Django Form won't render
Django: Permissions granted to auth user but not there in view / template?
How do I reset the django cache for static file names?
Apache HTTP Basic Auth - 401 error after supplying username and password
Unable to load require.config dependency when using with Django
How i can show list of objects that have no related object?
Using mixins in class based view - Django
Can I specify a multiline context variable/parameter when {% include %}ing a template?
Django admin panel throws 404 when passing any url parameters