gpt4 book ai didi

python - Django累积总和或运行总和

转载 作者:行者123 更新时间:2023-12-02 18:32:39 25 4
gpt4 key购买 nike

我正在尝试制作一个派对分类帐。哪些详细信息将按日期搜索结果显示。我有一个列名称平衡,它将按日期搜索显示累积数据。我想查看表格中的 cumbalance 列,具体取决于余额列。

               --------------------------------------
amount payment balance CumBalance
--------------------------------------
10 5 5 5
20 5 15 20
10 15 -5 15

我的看法:

def partyDetails(request,pk):
form = DateRangeForm()
if request.method == 'POST':
form = DateRangeForm(request.POST or None)
if form.is_valid():
cumulative_balance = PurchasePayment.objects.all()
.filter(vendor=pk,date__range=
(form.cleaned_data['start_date'],
form.cleaned_data['end_date']))
.annotate(cumbalance =Sum('balance'))
else:
return redirect('party_ledger')
return render(request, 'purchase/party_details.html',
{'dateform':form,
'cumbal':cumulative_balance,'name':pk})

我也尝试过.aggregate(Sum('balance'))

我的模型:

class PurchasePayment(models.Model):
id = models.AutoField(primary_key=True)
date = models.DateField(default=date.today)
invoice = models.CharField(max_length=20)
vendor = models.CharField(max_length=50)
amount = models.DecimalField(max_digits=9,
decimal_places=2, default=0.00)
discount = models.DecimalField(max_digits=9,
decimal_places=2, default=0.00)
payment = models.DecimalField(max_digits=9,
decimal_places=2, default=0.00)
balance = models.DecimalField(max_digits=9,
decimal_places=2)

最佳答案

截至您可以使用 Window expression [Django-doc] :

from django.db.models import F, Sum, Window

cumulative_balance = PurchasePayment.objects.filter(
vendor=pk,
date__range=(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
).order_by('pk').annotate(
cumbalance=<strong>Window(</strong>Sum('balance')<strong>, order_by=F('id').asc())</strong>
)

关于python - Django累积总和或运行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69227749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com