Reece Hewitson
Reece Hewitson

Reputation: 101

using sum() to find the aggregated price in a list of items

I have a list of items "display_list" which contains products, these products have a field called "pro price" in them which is the price of the product in the list.

If I have a display list with 2 apples and a banana, for example, I want to work out the aggregate price of the 2 apples and banana, how would I go about doing this?

I have currently tried

total = sum([(pro.proprice for pro in display_list)])

but this isn't working, would anyone be able to lend a hand? Thanks in advance

Upvotes: 0

Views: 85

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You write brackets in the list comprehension, as a result you make a list containing one element: a generator. You can not take the sum of one generator.

You can do two things: either pass a generator to sum(..), or you can first generate a list and pass it to the sum(..), so:

total = sum([pro.proprice for pro in display_list])

or:

total = sum(pro.proprice for pro in display_list)

That being said, if display_list is a QuerySet, you can use aggregation:

# if display_list is a QuerySet
from django.db.models import Sum

total = display_list.aggregate(total=Sum('proprice'))['total']

Upvotes: 4

Agile_Eagle
Agile_Eagle

Reputation: 1839

Try this: total = sum([pro.proprice for pro in display_list])

Upvotes: 1

Related Questions