Cumulative (running) sum with django orm and postgresql

前端 未结 5 906
你的背包
你的背包 2021-01-05 14:24

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

class AModel(models.Model):
    a_number = models         


        
5条回答
  •  醉话见心
    2021-01-05 14:56

    For reference, starting with Django 2.0 it is possible to use the Window function to achieve this result:

    AModel.objects.annotate(cumsum=Window(Sum('a_number'), order_by=F('id').asc()))\
                  .values('id', 'cumsum').order_by('id', 'cumsum')
    

提交回复
热议问题