2

I want to get the row wise sum of all previous value in column amount.

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)

I tried the queryset

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

I want the result like this

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

3 Answers 3

2

On Django>=2 and on a supported DB, you can use the Window function to get the accumuation:

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
  • I'm using mysql 5.7 getting a syntax error near '(ORDER BY account_paymentrecord.id ASC) AS SumAmount FROM `account_payment' Commented Nov 14, 2019 at 12:33
0

You probably will achieve what you want with the following:

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')
-1

You can try this is simply code for you hopefully it will work!

query = ModelName.objects.aggregate(Sum('field_name'))
context = {'query':query}
reutrn render(request,'your_template_name',context)

in html file:

<td>{{ query}}</td>
6
  • I want the result row wise. Commented Nov 14, 2019 at 11:55
  • @SachinSingh Try This it will also work for row wise Commented Nov 14, 2019 at 11:56
  • i am getting a result in form of dict. {'amount__sum': 157925.0} how can i print the table which i have mentioned above. Commented Nov 14, 2019 at 12:00
  • You can add simply context and add in your html file Commented Nov 14, 2019 at 12:01
  • can you please share a snippet how to do that. Commented Nov 14, 2019 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.