Cumulative (running) sum with django orm and postgresql

前端 未结 5 905
你的背包
你的背包 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:59

    You can try to do this with Func expression.

    from django.db.models import Func, Sum
    
    AModel.objects.annotate(cumsum=Func(Sum('a_number'), template='%(expressions)s OVER (PARTITION BY %(partition_by)s)', partition_by='id')).values('id', 'cumsum').order_by('id')
    

提交回复
热议问题