Django SUM 查询?

发布于 2024-11-17 02:16:08 字数 284 浏览 1 评论 0原文

我有一个类似于以下内容的查询:

SELECT SUM(name) FROM table WHERE name IS NULL

How does that SUMtranslate into a QuerySet in Django?即它会转换为什么操作xyz,例如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()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江湖彼岸 2024-11-24 02:16:08

更新:以下内容合并了原始查询的 ISNULL 方面:

from django.db.models import Sum

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

您正在寻找 Sum 聚合函数,其工作原理如下:

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

请参阅:https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum

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

小瓶盖 2024-11-24 02:16:08

您还可以为返回值设置别名:

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

返回一个字典,例如 {'total': 12345}

如果您需要过滤要求和的值,另一种方法是通过 Q 对象使用 Sum 对象的 filter= 参数。以下命令返回 field_1 值的总和,其中对应的 field_2 值为 null,即相当于 SQL 查询 SELECT SUM(field_1) FROM table WHERE field_2 IS空。

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

您还可以使用字典来存储总和,并在传递给 aggregate() 时将其解包为关键字参数。

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

两者都返回一个字典,例如 {'total': 1234}

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}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文