213👍
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
0👍
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}
.
- [Django]-Django development IDE
- [Django]-Django Footer and header on each page with {% extends }
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."