Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add decimal.Decimal values in Django?

Tags:

python

django

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?

like image 546
proprogrammer Avatar asked Dec 11 '25 20:12

proprogrammer


1 Answers

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
like image 193
Alasdair Avatar answered Dec 13 '25 09:12

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!