我想获取列数量中所有先前值的按行求和。
models.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
答案 0 :(得分:0)
在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')
答案 1 :(得分:0)
您可能会通过以下方法实现您想要的:
from django.db.models import Window, Sum
PaymentRecord.objects.filter(...).annotate(
SumAmount=Window(
Sum(F('amount')),
partition_by=F('paid_into'),
order_by=F('payment_date').asc()
)
).values('id', 'paid_into', 'payment_date', 'amount', 'SumAmount')
答案 2 :(得分:-1)
您可以尝试这只是简单的代码,希望它能起作用!
query = ModelName.objects.aggregate(Sum('field_name'))
context = {'query':query}
reutrn render(request,'your_template_name',context)
在 html文件中:
<td>{{ query}}</td>