return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date) or 0)
views:
335answers:
3
+3
A:
After a small rewrite
query = self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date)
values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )
return sum( values )
Look closely at the values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )
What happens when the query is empty?
You're evaluating jobrecord.get_cost() or 0 for jobrecord in 0
S.Lott
2009-03-19 01:42:52
A:
Mr. Lott!
Thank you. What if put the or 0
on the outside of the parenthesis, as below?
return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date)) or 0
Antonius Common
2009-03-19 02:08:21
How many `or 0`'s do you need? What are you trying to do?
S.Lott
2009-03-19 02:10:32
Ha! I'm probably not sure... just being Irish "to be sure to be sure"so get rid of the final `or 0` huh?
Antonius Common
2009-03-19 02:21:42
@Antonius Common: If you can't articulate the reasoning, you have work to do. If you take the time to clearly articulate the desired result, you can easily reason out the code.
S.Lott
2009-03-19 02:25:09
Good point, I'd just learnt this idiom from someone else, so I'm still learning the mechanisms of python. Thanks for the help!
Antonius Common
2009-03-19 03:34:47
+1
A:
0 is indeed not iterable. I think you want to drop that last or 0
. when the filter query matches no elements, it will return an empty query, and your sum will just be 0, since sum([])
is zero.
If there's some reason why the query might raise an exception (invalid dates or some such), an or clause wont catch that either. [][1] or 0
still raises an exception.
TokenMacGuy
2009-03-19 02:13:33