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()?
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()?
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
result = ModelName.objects.aggregate(total=Sum('field_name'))['total']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}.