Django cumulative sum or running sum

Question:

I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. I want to view cumbalance column in my table depends on balance column.

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

My view:

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})

I have also tried .aggregate(Sum('balance'))

my model:

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)
Asked By: Shanzedul

||

Answers:

As of you can use a 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=Window(Sum('balance'), order_by=F('id').asc())
)
Answered By: Willem Van Onsem

How we can save this annotated value (cumbalance) in database, as i need to query

Answered By: Shanila Afaq
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.