首页 > 解决方案 > django postgresql 累计和

问题描述

我正在尝试制作派对账本。日期搜索结果将显示哪些详细信息。我有一个列名 balance ,它将按日期搜索显示累积数据。余额字段是一个小数字段。我正在views.py中尝试以下内容

          def partyDetails(request,pk):
               form = DateRangeForm()
               search = []
               until = []
               cumbalance = 0.00
               if request.method == 'POST':
                   form = DateRangeForm(request.POST or None)
                     if form.is_valid():
                     search = PurchasePayment.objects.filter(vendor=pk,date__range=(
                       form.cleaned_data['start_date'],
                       form.cleaned_data['end_date']
                      ))
                     for balancet in search:
                        cumbalance += Decimal(balancet.balance)

           else:
              return redirect('party_ledger')
           return render(request, 'purchase/party_details.html', {'dateform':form, 
                         'party':search,'name':pk, 'cumbalance':cumbalance})

但是我收到错误unsupported operand type(s) for += If I try cumbalance += [balancet.balance] then get [Decimal('200000.00'), Decimal('-200000.00')] MY Models.py 给出如下

  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)
        remarks = models.TextField(blank=True)
        extra = models.CharField(max_length=100, blank=True)

         def __str__(self):
           return self.vendor

我的 HTML

                        <tbody>
                              {% for data in party %}
                              {% for cum in cumbalance %}
                           <tr>
                            <td >{{data.date}}</td>
                            <td >{{data.invoice}}</td>
                            <td >{{data.amount}}</td>
                            <td >{{data.discount}}</td>
                            <td >{{data.payment}}</td>
                            <td >{{cum}}</td>                               
                        </tr>
                         {% endfor %}
                         {% endfor %}
                         </tbody>

如何在余额字段中进行累积视图

标签: pythondjangopostgresqlcumulative-sum

解决方案


你试过使用aggregate吗?

cumulative_balance = PurchasePayment.objects.filter(vendor=pk,date__range=(form.cleaned_data['start_date'], form.cleaned_data['end_date']).aggregate(Sum('balance'))

然后访问您使用的值cumulative_balance['balance']


推荐阅读