2016-12-21 25 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()) 
相關問題