Django SUM 查询? ?

我有一个类似如下的疑问:

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

在姜戈,SUM如何转换成 QuerySet?也就是说。在类似于 MyModel.objects.xyz()的情况下,xyz操作翻译成什么?

122628 次浏览

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