1

I have a query set that contains a number of transactions for a particular product.

transactions = Transaction.objects.filter(product__product_name_id = item.id)

Within this queryset contains a number of fields.

product
amount
price
transaction_date

I need to calculate the totals of the values in the amount fields.

The current query set is returning 2 amounts from 2 `transactions'

Would it be sensible to loop through each transaction and add it to a list of something? or is there a better way?

list = []
for item in transactions:
   amount = item.amount
   list.append(amount)

Thanks

JacksWastedLife
  • 254
  • 2
  • 15
  • You could try an sum-annotation: https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#following-relationships-backwards – Leeuwtje Feb 07 '22 at 09:22
  • Does this answer your question? [Django: Calculate the Sum of the column values through query](https://stackoverflow.com/questions/8616343/django-calculate-the-sum-of-the-column-values-through-query) – PTomasz Feb 07 '22 at 09:33

2 Answers2

2

You can let the db handle this by using aggregation:

from django.db.models import Sum

total = transactions.aggregate(s=Sum("amount"))["s"]
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

you can use aggregate for doing that:

from django.db.models import Sum

transactions.aggregate(Sum('amount'))
# returns {'amount__sum': 1000} for example
armin shoughi
  • 74
  • 1
  • 4