开发者

Catching 'NoneType' exceptions in the work with DateTimeFields

I have the following views.py code.

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 = 'stactio开发者_Python百科n_day'
        else:
            r.time_action_status = 'non_staction_day'

Sometimes I get an error, because some date_of_notification in request is empty(NoneType):

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

models.py:

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

What kind of validation for r.date_of_notification should I use, to avoid mistakes?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜