Django and Aggregate: Sum of distinct values?

2020-02-25 08:16发布

I am trying to do a django aggregate function, but am unable to produce the desired result.

What I've got:

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 'amount' fields that have the same category__name.

4条回答
放我归山
2楼-- · 2020-02-25 08:47

Just to add to arjun27's answer. Since that package seems to have been abandoned you might want to just copy past the 3 lines you need from it:

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

Which can be used the same as above:

income_posts.annotate(total=DistinctSum('amount')
查看更多
等我变得足够好
3楼-- · 2020-02-25 09:04

From this answer for a related question:

from django.db.models import Sum
income_posts.values('category__name').order_by('category__name').annotate(total=Sum('amount'))
查看更多
劫难
4楼-- · 2020-02-25 09:04

If you are on Postgres, you can use the django-pg-utils package for sum of distinct values.

from pg_utils import DistinctSum
income_posts.annotate(total=DistinctSum('amount')
查看更多
Fickle 薄情
5楼-- · 2020-02-25 09:05

Django 3.0 introduced "distinct=True" on Sum and Avg: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#sum

查看更多
登录 后发表回答