我试图添加一些值,但有些值具有NoneType值。现在我看了这个question,但我需要一些帮助。我希望有人可以向我解释如何让这个与django一起工作。
这是我的views.py中的for循环:
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 += inv.maturity_amount
现在,inv.maturity_amount是我正在尝试处理的具有NoneType的值。
任何建议都将不胜感激。
感谢。
史蒂夫
答案 0 :(得分:6)
for inv in next_il:
total_m2 += inv.maturity_amount or 0
可能您应该为default=0
字段设置maturity_amount
。
最好在这里使用DB aggregation:
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'))
答案 1 :(得分:0)
我有两种选择。
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
我其实更喜欢这个:
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" )