2016-12-21 63 views
-1

我的字段在我的django应用程序live_fromlive_to这些字段是不需要的。TypeError:无法订购的类型:无类型()<= datetime.datetime()

字段:当此字段为空,我在梅托德得到一个错误

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() <= datetime.datetime()

+0

看起来不像编码错误,更像是设计错误。如果这些字段是空的,'is_live'应该做什么? – TigerhawkT3

+0

因此,无论是'live_from'还是'live_to'都是None,因为您允许使用空值。 'life_from'这个例外看起来是'None',但这同样适用于'live_to'。如果其中任何一个都是空的,会发生什么? –

回答

2

我想你想将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()) 
+0

作品,谢谢:) –

1

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

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()) 
相关问题