开发者

Catching 'NoneType' exceptions in the work with DateTimeFields

开发者 https://www.devze.com 2023-03-10 19:30 出处:网络
I have the following views.py code. now_time = datetime.datetime.now() for r in requests: hmt = r.date_of_notification - now_time

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

精彩评论

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

关注公众号