3👍
✅
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
Source:stackexchange.com