我对django的看法如下:
reviews = singles.review_set.all()
for rev in reviews:
print rev.sentiment
print type(rev.sentiment)它返回decimal.Decimal,但我需要计算数字的和。
当我尝试sum(rev.sentiment)时,我得到了错误'Decimal' object is not iterable。我怎样才能解决这个问题?
发布于 2015-09-08 11:48:02
您想要将几个值相加。但是,rev.sentiment是一个单一的值,因此您可以得到TypeError,因为它没有意义。
您可以在for循环中构建一个和:
rev_sum = 0
for rev in reviews:
rev_sum += rev.sentiment或者用一种理解。
rev_sum = sum(rev.sentiment for rev in reviews)如果您有许多对象,那么使用聚合在数据库中进行和可能会更有效。
from django.db.models import Sum
aggregate = reviews.aggregate(Sum('sentiment'))
rev_sum = aggregate['sentiment__sum'] # retrieve the value from the dicthttps://stackoverflow.com/questions/32456992
复制相似问题