Django SUM Query?

PythonDjangoDjango Queryset

Python Problem Overview


I have a query akin to the following:

SELECT SUM(ISNULL(table.name)) FROM table

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()?

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser541686View Question on Stackoverflow
Solution 1 - Pythonrolling stoneView Answer on Stackoverflow