I have django views:
reviews = singles.review_set.all()
for rev in reviews:
print rev.sentiment
print type(rev.sentiment)
It returns decimal.Decimal but I need to calculate the sum of the numbers.
When I try sum(rev.sentiment), I get error 'Decimal' object is not iterable. How can I fix this problem?
You want to sum several values. Howver, rev.sentiment is a single value, so you get the TypeError as it doesn't make sense to sum it.
You can either build a sum in the for loop:
rev_sum = 0
for rev in reviews:
rev_sum += rev.sentiment
Or use a comprehension.
rev_sum = sum(rev.sentiment for rev in reviews)
If you have many objects, it might be more efficient to do the sum in the database using aggregation.
from django.db.models import Sum
aggregate = reviews.aggregate(Sum('sentiment'))
rev_sum = aggregate['sentiment__sum'] # retrieve the value from the dict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With