Django模型返回NoneTyp

2024-04-26 22:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型产品

它有两个字段大小和颜色

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?我如何测试它?


Tags: 模型truesizelen产品颜色modelscurrent
3条回答

NoneType是Pythons空类型,意思是“nothing”,“undefined”。它只有一个值:“无”。创建新模型对象时,其属性通常初始化为“无”,可以通过比较来检查:

if someobject.someattr is None:
    # Not set yet

NoneTypeNone值所具有的类型。要将第二个片段更改为

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

我可以用这个错误代码的例子来解释非类型错误:

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))  

相关问题 更多 >