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?
You shouldn't be returning a generator at all here. The generator should be the input to the sum function.
At the moment, you're effectively creating a list of items, each of which is the "sum" of a single value. That's why you get the error about not iterable; it's cd.count
that is not iterable, because it's a single value and you can't sum that.
I suspect what you meant was to sum all the counts:
deaths = sum(cd.count for cd in ChickenDeath.objects.filter(...))
but that is not the right thing to do. You should ask the database to do the sum for you:
from django.db.models import Sum
deaths = ChickenDeath.objects.filter(...).aggregate(total=Sum('count'))
print(deaths['total'])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments