Django SUM Query?

Question:

I have a query akin to the following:

SELECT SUM(name) FROM table WHERE name IS NULL

How does that SUM translate into a QuerySet in Django? i.e. What operation xyz does it translate to, in something like MyModel.objects.xyz()?

Asked By: user541686

||

Answers:

Update: The following incorporates the ISNULL aspect of the original query:

from django.db.models import Sum

ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))
# returns {'field_name__sum': 1000} for example

You’re looking for the Sum aggregation function, which works as follows:

ModelName.objects.aggregate(Sum('field_name'))

See: https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum

Answered By: rolling stone

You can also alias the returned value:

MyModel.objects.aggregate(total=Sum('field_1'))

which returns a dictionary such as {'total': 12345}.

If you need to filter the values to be summed over, another way is to use the filter= parameter of the Sum object via the Q object. The following returns the total of field_1 values where the corresponding field_2 values are null, i.e. the equivalent of the SQL query SELECT SUM(field_1) FROM table WHERE field_2 IS NULL.

from django.db.models import Q, Sum
MyModel.objects.aggregate(total=Sum('field_1', filter=Q(field_2__isnull=True)))

You can also use a dictionary to store the sum and unpack as keyword arguments when passed to aggregate().

dct = {'total': Sum('field_1', filter=Q(field_2__isnull=True))}
MyModel.objects.aggregate(**dct)

both of which return a dictionary such as {'total': 1234}.

Answered By: cottontail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.