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

标签 python django postgresql

我正在尝试制作一个派对分类帐。哪些详细信息将按日期搜索结果显示。我有一个列名称平衡,它将按日期搜索显示累积数据。我想查看表格中的 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/

相关文章:

c# - 当数组参数的值为空时,无法确定其类型

sql - 插入或更新另一个表时更新表中列的 Postgresql 触发器

python - 按值对字符串排序并添加到列表

python - 为什么这个 python 正则表达式不能编译?

python - 哪个 pip 与哪个 python 一起使用?

javascript - 是否有依赖于 chrome 而不是 safari 的 pywebview 替代品

mysql - 如何从我的 django 网站连接到集中式 MySQL 数据库?

python - Django:获取某个用户所在的 session 列表

mysql - 列索引的有效性是否与列数据的熵有关

python - 在 Pandas python 中使用 nrow 跳过第一行时出现意外结果