Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum total value for all items

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can let the db handle this by using aggregation:

from django.db.models import Sum

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading