首页 > 解决方案 > 如何使用 django 查询集获取列中所有先前值的逐行总和

问题描述

我想获得列数量中所有先前值的逐行总和。

模型.py

class PaymentRecord(models.Model):
    invoice_no = models.ForeignKey(Invoice, unique=False, related_name='paymentrecord', on_delete=models.CASCADE)
    amount = models.CharField(max_length=10)
    paid_into = models.CharField(max_length=40, choices=PAID)
    payment_date = models.DateField(auto_now=False, auto_now_add=False)
    cheque_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
    cheque_no = models.CharField(max_length=20, null=True, blank=True)
    notes = models.CharField(max_length=100, null=True, blank=True)

我尝试了查询集

pay_receipt = PaymentRecord.objects.filter(Q(payment_date__range=[startdate, enddate]),Q(paid_into='ONLINE') | Q(paid_into='CHEQUE')).annotate(totals=Sum('amount')).order_by('payment_date')

我想要这样的结果

Id   paid_into   payment_date   amount    SumAmount
---------------------------------------------------------
1     ONLINE      12-09-2019        40.00     40.00
2     ONLINE      12-09-2019        40.00     80.00
3     ONLINE      12-09-2019        45.00     125.00         
4     ONLINE      12-09-2019        50.00     175.00

标签: djangodjango-modelsdjango-queryset

解决方案


在 Django>=2 和受支持的数据库上,您可以使用该Window函数来获取累积:

from django.db.models import Window, Sum

PaymentRecord.objects.filter(...).annotate(
    SumAmount=Window(Sum(F('amount')), order_by=F('pk').asc())
).values('id', 'paid_into', 'payment_date', 'amount', 'SumAmount')

推荐阅读