How to get singular value from a generator?

时间:2018-04-28 17:54:43

标签: django python-3.x django-models python-3.6

I'm writing an app to monitor chicken deaths in a poultry farm and have the following code:

today = datetime.date.today()
deaths = (sum(cd.count) for cd in ChickenDeath.objects.filter(date__gte=datetime.date(today.year, today.month, 1)))
print(deaths)

My problem is it just prints out <generator object chickens_overview.<locals>.<genexpr> at 0x110010678> instead of the actual sum. I've tried next(deaths) as well however I just get the error 'int' object not iterable. Is there another way to get the value from this generator?

1 个答案:

答案 0 :(得分:3)

你根本不应该返回发电机。生成器应该是sum函数的输入。

目前,您正在有效地创建一个项目列表,每个项目都是&#34;总和&#34;单一价值。这就是为什么你得到关于不可迭代的错误的原因;它不是可迭代的cd.count,因为它是单个值而你无法对此进行求和。

我怀疑你的意思是总结所有的计数:

deaths = sum(cd.count for cd in ChickenDeath.objects.filter(...))

但这不是正确的做法。你应该让数据库为你做总结:

from django.db.models import Sum
deaths = ChickenDeath.objects.filter(...).aggregate(total=Sum('count'))
print(deaths['total'])