django - 如何使用 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
解决方案
在 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')
推荐阅读
- reactjs - ReactJS:表单提交后重定向而不刷新
- tf.data.dataset - tf.data.dataset.from_tensor_slices 用于 RNN 模型
- csound - 导出到 midi 文件时如何计算 Csound 中的 midi 时间?
- javascript - 带有反应的谷歌分析不起作用
- java - 403 禁止 - Spring Security
- git - 如何在 Windows 中基于文件夹设置和切换两个 Github 账户?
- c# - C# 应用程序测试连接(ping、下载、上传)到 Web 服务
- python - url中的下一个参数未显示但在django中正确打印
- android - 如何使图像适合 CardView 的大小
- aws-lambda - Cloudformation:通过 API GW 集成发现 Lambda 函数的权限无效