django orm和postgresql的累积(运行)总和

编程入门 行业动态 更新时间:2024-10-28 15:19:42
本文介绍了django orm和postgresql的累积(运行)总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以使用Django的orm计算累积(运行)总和?考虑以下模型:

Is it possible to calculate the cumulative (running) sum using django's orm? Consider the following model:

class AModel(models.Model): a_number = models.IntegerField()

带有一组数据,其中a_number = 1.这样,我在数据库中就有数量(> 1)个AModel实例,全部带有a_number=1.我希望能够返回以下内容:

with a set of data where a_number = 1. Such that I have a number ( >1 ) of AModel instances in the database all with a_number=1. I'd like to be able to return the following:

AModel.objects.annotate(cumsum=??).values('id', 'cumsum').order_by('id') >>> ({id: 1, cumsum: 1}, {id: 2, cumsum: 2}, ... {id: N, cumsum: N})

理想情况下,我希望能够限制/过滤累计金额.因此,在上述情况下,我想将结果限制为cumsum <= 2

Ideally I'd like to be able to limit/filter the cumulative sum. So in the above case I'd like to limit the result to cumsum <= 2

我相信在postgresql中,可以使用窗口函数来实现累加和.如何将其转换为ORM?

I believe that in postgresql one can achieve a cumulative sum using window functions. How is this translated to the ORM?

推荐答案

根据Dima Kudosh的回答,并基于 stackoverflow. com/a/5700744/2240489 我必须执行以下操作: 我在sql中删除了对PARTITION BY的引用,并替换为ORDER BY结果.

From Dima Kudosh's answer and based on stackoverflow/a/5700744/2240489 I had to do the following: I removed the reference to PARTITION BY in the sql and replaced with ORDER BY resulting in.

AModel.objects.annotate( cumsum=Func( Sum('a_number'), template='%(expressions)s OVER (ORDER BY %(order_by)s)', order_by="id" ) ).values('id', 'cumsum').order_by('id', 'cumsum')

这将给出以下sql:

SELECT "amodel"."id", SUM("amodel"."a_number") OVER (ORDER BY id) AS "cumsum" FROM "amodel" GROUP BY "amodel"."id" ORDER BY "amodel"."id" ASC, "cumsum" ASC

Dima Kudosh的答案不是对结果求和,但是上面的结果.

Dima Kudosh's answer was not summing the results but the above does.

更多推荐

django orm和postgresql的累积(运行)总和

本文发布于:2023-10-15 11:49:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   django   orm   postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!