使用DateTimeFields捕获'NoneType'异常

时间:2011-06-05 21:32:40

标签: django

我有以下views.py代码。

now_time = datetime.datetime.now()
for r in requests:
        hmt = r.date_of_notification - now_time
        if hmt <= datetime.timedelta(days = 1):
            r.time_action_status = 'staction_day'
        else:
            r.time_action_status = 'non_staction_day'

有时我会收到错误,因为请求中的某些date_of_notification为空(NoneType):

TypeError: unsupported operand type(s) for -: 'NoneType' and 'datetime.timedelta'

models.py:

date_of_notification = models.DateTimeField(blank=True, null=True)

我应该使用r.date_of_notification进行哪种验证,以避免错误?

1 个答案:

答案 0 :(得分:2)

if r.date_of_notification is not None:
  do_something_useful()
else:
  field_is_null()