2011-06-05 58 views
0

我有以下views.py代码。使用DateTimeFields捕获'NoneType'异常

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我应该使用,以避免错误?

回答

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