Django SUM 查询?
我有一个类似于以下内容的查询:
SELECT SUM(name) FROM table WHERE name IS NULL
How does that SUM
translate 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:以下内容合并了原始查询的 ISNULL 方面:
您正在寻找 Sum 聚合函数,其工作原理如下:
请参阅:https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum
Update: The following incorporates the ISNULL aspect of the original query:
You're looking for the Sum aggregation function, which works as follows:
See: https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum
您还可以为返回值设置别名:
返回一个字典,例如
{'total': 12345}
。如果您需要过滤要求和的值,另一种方法是通过
Q
对象使用Sum
对象的filter=
参数。以下命令返回field_1
值的总和,其中对应的field_2
值为 null,即相当于 SQL 查询SELECT SUM(field_1) FROM table WHERE field_2 IS空。
您还可以使用字典来存储总和,并在传递给
aggregate()
时将其解包为关键字参数。两者都返回一个字典,例如
{'total': 1234}
。You can also alias the returned value:
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 theSum
object via theQ
object. The following returns the total offield_1
values where the correspondingfield_2
values are null, i.e. the equivalent of the SQL querySELECT SUM(field_1) FROM table WHERE field_2 IS NULL
.You can also use a dictionary to store the sum and unpack as keyword arguments when passed to
aggregate()
.both of which return a dictionary such as
{'total': 1234}
.