Im trying to add some values up but some of the values have a NoneType value. Now I looked at this question but I need some help. Im hoping someone can explain to me how I can get this to work with django.
Here is my for loop in my views.py:
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_ye开发者_StackOverflowar)
for inv in next_il:
total_m2 += inv.maturity_amount
Now inv.maturity_amount is the value I'm trying to handle that has NoneType.
Any suggestions would be greatly appreciated.
Thanks.
Steve
for inv in next_il:
total_m2 += inv.maturity_amount or 0
And may be you should set default=0
for maturity_amount
field.
And it's better to use DB aggregation here:
from django.db.models import Sum
total_m2 = Investment.objects.filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year).aggregate(Sum('maturity_amount'))
Two choices that occur to me.
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year)
for inv in next_il:
total_m2 += 0 if inv.maturity_amount is None else inv.maturity_amount
I actually like this better:
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year)
for inv in next_il:
try:
total_m2 += inv.maturity_amount
except TypeError:
log.warning( "Null maturity amount" )
精彩评论