使用添加时处理NoneType

The*_*eve 0 python django django-models django-views

我试图添加一些值,但有些值具有NoneType值.现在我看了这个问题,但我需要一些帮助.我希望有人可以向我解释如何让这个与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
Run Code Online (Sandbox Code Playgroud)

现在,inv.maturity_amount是我试图处理的具有NoneType的值.

任何建议将不胜感激.

谢谢.

史蒂夫

DrT*_*rsa 6

for inv in next_il:
   total_m2 += inv.maturity_amount or 0
Run Code Online (Sandbox Code Playgroud)

也许你应该default=0maturity_amount场地设定.

最好在这里使用数据库聚合:

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'))
Run Code Online (Sandbox Code Playgroud)