我有一个模型产品

它具有除其他两个字段的大小和颜色

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以及如何测试呢?

有帮助吗?

解决方案

NoneType在于None值具有的类型。你想第二个片段更改为

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

其他提示

NoneType是蟒NULL型,意为 “无”, “未定义”。它只有一个值:“无”。当创建一个新的模型对象,则其属性通常初始化为无,则可以通过比较检查:

if someobject.someattr is None:
    # Not set yet

我能最好地解释本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))  

我不知道Django的,但我认为某种ORM的参与,当你做到这一点:

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

此时,您应经常检查是否获得无回(“无”是一样的在Java中“空”或Lisp的“零”与微妙的区别在于“无”是在Python的对象)。这通常是奥姆斯的方式映射空集到的编程语言。

修改: 哎呀,我只看到它的current_product.sizeNonecurrent_product。至于说,我不熟悉Django的ORM,但是这仍似乎很奇怪:我要么期望current_productNone或具有数值size

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top