Django and Aggregate: sum of different values?

I am trying to execute the django aggregation function, but cannot get the desired result.

What I have:

income_posts.values_list('category__name','amount') [(u'Donation', Decimal("2000.00")), (u'Paycheck', Decimal("1200.00")), (u'Donation', Decimal("1000.00"))] 

Desired Result:

 [(u'Donation', Decimal("3000.00")), (u'Paycheck', Decimal("1200.00))] 

I need to sum the β€œquantity” fields that have the same category name.

+9
django django-orm
source share
3 answers

From this answer on a related question :

 from django.db.models import Sum income_posts.values('category__name').order_by('category__name').annotate(total=Sum('amount')) 
+15
source share

If you use Postgres, you can use the django-pg-utils package to sum the various values.

 from pg_utils import DistinctSum income_posts.annotate(total=DistinctSum('amount') 
+3
source share

Just to add an answer to arjun27. Since this package seems to have been abandoned, you can simply copy 3 necessary lines from it:

 from django.db.models import Sum class DistinctSum(Sum): function = "SUM" template = "%(function)s(DISTINCT %(expressions)s)" 

Which can be used in the same way as above:

 income_posts.annotate(total=DistinctSum('amount') 
0
source share

All Articles