tags:

views:

335

answers:

3
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)
+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
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
How many `or 0`'s do you need? What are you trying to do?
S.Lott
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
@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
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
+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