2009-02-16 105 views
2

我有一個模型產品Django模塊返回NoneType

它有兩個字段的大小等等

colours = models.CharField(blank=True, null=True, max_length=500) 
size = models.CharField(blank=True, null=True, max_length=500) 

在我看來,我有

current_product = Product.objects.get(slug=title) 
if len(current_product.size) != 0 : 
    current_product.size = current_product.size.split(",") 

,並得到這個錯誤&顏色:

'NoneType'類型的對象沒有len()

什麼是NoneType?我該如何測試它?

+2

「類型爲NoneType的對象」是您可以在Python文檔中查找的東西。這是不變的無。該模型不返回「NoneType」,它返回None,它是NoneType的一個對象。 – 2009-02-16 11:17:36

回答

7

NoneTypeNone值的類型。您想將第二個片段更改爲

if current_product.size: # This will evaluate as false if size is None or len(size) == 0. 
    blah blah 
+0

乾杯, 我以爲我試過。這就是我試圖測試長度的原因。呃,好吧。你在大工作上得到這個 – 2009-02-16 07:52:52

+0

你這樣做。我喜歡這個成語 - 它消除了使得代碼更不可讀的「或」,並且這很容易被忽略(如圖所示:)) – ruds 2009-02-16 08:30:25

+0

請使用「不是無」而不是假設無是假 - 它使if語句完全清晰。 – 2009-02-16 11:10:41

1

NoneType是Pythons NULL-Type,意思是「nothing」,「undefined」。它只有一個值:「無」。當創建一個新的模型對象,它的屬性通常被初始化爲None,您可以檢查通過比較:

if someobject.someattr is None: 
    # Not set yet 
-1

我不知道Django的,但我認爲某種ORM的參與,當你做到這一點:

current_product = Product.objects.get(slug=title) 

此時,您應經常檢查你是否獲得無回(「無」是相同的Java「空」或Lisp的「零」與微妙的區別在於「無」是一個對象在Python中)。這通常是ORM將空集映射到編程語言的方式。

編輯: 哎呀,我只看到它的current_product.sizeNonecurrent_product。如上所述,我並不熟悉Django的ORM,但是這看起來很奇怪:我期望current_productNonesize有數字值。

0

我能與最好的錯誤代碼,這個例子說明NoneType錯誤:

def test(): 
    s = list([1,'',2,3,4,'',5]) 
    try: 
     s = s.remove('') # <-- THIS WRONG because it turns s in to a NoneType 
    except: 
     pass 
    print(str(s)) 

s.remove()返回任何又稱NoneType。正確的方法

def test2() 
    s = list([1,'',2,3,4,'',5]) 
    try: 
     s.remove('') # <-- CORRECTED 
    except: 
     pass 
    print(str(s))