Raisul Islam
Raisul Islam

Reputation: 1581

calculation sum of a django model field

class Transaction:
    amount = models.FloatField()

Now I calculate the sum of amount

transactions = Transaction.objects.all()
amount = 0
for transaction in transactions:
    balance = transaction.amount
    amount += balance

I know it is calculate by using agreegate. But is this possible by this way or another way ?

Upvotes: 0

Views: 820

Answers (2)

Abhishek Agarwala
Abhishek Agarwala

Reputation: 754

Not sure why not use aggregate, if you wanna iterate you can try

transactions = Transaction.objects.values_list('amount', flat=True)
amount = sum(list(transactions))

Upvotes: 0

Dan Moica
Dan Moica

Reputation: 274

ModelName.objects.aggregate(Sum('field_name'))

Here is the doc

Upvotes: 3

Related Questions