Home > Software design >  Sum total value for all items
Sum total value for all items

Time:02-07

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

CodePudding user response:

You can let the db handle this by using aggregation:

from django.db.models import Sum

total = transactions.aggregate(s=Sum("amount"))["s"]

CodePudding user response:

you can use aggregate for doing that:

from django.db.models import Sum

transactions.aggregate(Sum('amount'))
# returns {'amount__sum': 1000} for example
  •  Tags:  
  • Related