【问题标题】:TypeError: unorderable types: NoneType() <= datetime.datetime()TypeError:不可排序的类型:NoneType() <= datetime.datetime()
【发布时间】:2016-12-21 10:53:39
【问题描述】:

我的 django 应用程序 live_fromlive_to 中有字段,这些字段不是必需的。当此字段为空时,我的方法中出现错误:

字段:

live_from = models.DateTimeField('live from', blank=True, null=True)

live_to = models.DateTimeField('live to', blank=True, null=True)

这是我的方法:

def is_live(self):
    return (self.live_from <= timezone.now()) and (self.live_to >= timezone.now())

错误:TypeError: unorderable types: NoneType() &lt;= datetime.datetime()

【问题讨论】:

  • 看起来不像是编码错误,更像是设计错误。如果这些字段为空,is_live 应该做什么?
  • 所以live_fromlive_to 都是None,因为您允许空值。 life_from 的例外情况在这里是 None,但同样适用于 live_to。如果其中任何一个为空,会发生什么?

标签: python django datetime


【解决方案1】:

我认为你想将NonType与当前时间进行比较,你应该在值为空时返回False,例如:

def is_live(self):
    if self.live_from is None or self.live_to is None :
        return False
    return (self.live_from <= timezone.now()) and (self.live_to >= timezone.now())

【讨论】:

    【解决方案2】:

    根据您的模型,这将是一个很好的定义。

    def is_live(self):
        # first, check the inexpensive precondition, before comparing date fields
        return ((None not in [self.live_from, self.live_to]) and 
                self.live_from <= timezone.now() and self.live_to >= timezone.now())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2018-06-05
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多