I have this model:
class Transfer(models.Model):
transfer_code = models.CharField(max_length=30, blank=True, null=True)
sender_name = models.CharField(max_length=30, blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
recipient_name = models.CharField(max_length=30, blank=True, null=True)
time_sent = models.DateTimeField(auto_now_add=True, auto_now=False)
received = models.BooleanField(default=False)
time_received = models.DateTimeField(auto_now_add=False, auto_now=False, null=True)
def __unicode__(self):
return self.transfer_code
This is my view where i want to calculate the total amount in the table:
def listtransfersall(request):
title = 'ALL TRANSFERS'
queryset = Transfer.objects.all()
for instance in queryset:
total = 0
total += instance.amount
print total
context = {
"title": title,
"queryset": queryset,
"total": total,
}
return render(request, "listtransfersall.html",context)
This prints the amount in the table individually. How can i get the total and assign it to the total variable?
In your posted code, you set total = 0 each time through the loop
for instance in queryset:
total = 0
total += instance.amount
print total
Move that line outside of the loop and this will work the way you intended.
Slightly better would be to get a values_list and sum that:
amounts = Transfer.objects.values_list('amount', flat=True)
total = sum(amounts)
Better still would be to let the database do the work and use the Sum aggregation:
from django.db.models import Sum
total = Transfer.objects.aggregate(Sum("amount"))
See the documentation for more information on aggregations
You can use annotate for that. In your case, try this:
from django.db.models import Sum
queryset = Transfer.objects.annotate(total_amount=Sum('amount'))
And then use in your template:
queryset.total_amount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With