python Django 模型返回 NoneType
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/552521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Model returning NoneType
提问by Cato Johnston
I have a model Product
我有一个模型产品
it has two fields size & colours among others
它有两个字段大小和颜色等
colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
In my view I have
在我看来,我有
current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
and get this error:
并收到此错误:
object of type 'NoneType' has no len()
'NoneType' 类型的对象没有 len()
What is NoneType and how can I test for it?
什么是 NoneType 以及如何测试它?
回答by ruds
NoneType
is the type that the None
value has. You want to change the second snippet to
NoneType
是None
值的类型。您想将第二个片段更改为
if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
回答by Ferdinand Beyer
NoneType is Pythons NULL-Type, meaning "nothing", "undefined". It has only one value: "None". When creating a new model object, its attributes are usually initialized to None, you can check that by comparing:
NoneType 是 Python 的 NULL-Type,意思是“没有”,“未定义”。它只有一个值:“无”。创建新的模型对象时,其属性通常初始化为None,您可以通过比较来检查:
if someobject.someattr is None:
# Not set yet
回答by baudsmoke
I can best explain the NoneType error with this example of erroneous code:
我可以用这个错误代码的例子来最好地解释 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()
returns nothing also known as NoneType. The correct way
s.remove()
不返回任何内容,也称为 NoneType。正确的方法
def test2()
s = list([1,'',2,3,4,'',5])
try:
s.remove('') # <-- CORRECTED
except:
pass
print(str(s))
回答by paprika
I don't know Django, but I assume that some kind of ORM is involved when you do this:
我不知道 Django,但我认为当你这样做时涉及某种 ORM:
current_product = Product.objects.get(slug=title)
At that point you should always check whether you get None back ('None' is the same as 'null' in Java or 'nil' in Lisp with the subtle difference that 'None' is an object in Python). This is usually the way ORMs map the empty set to the programming language.
在这一点上,您应该始终检查是否返回 None ('None' 与 Java 中的 'null' 或 Lisp 中的 'nil' 相同,其中的细微差别是 'None' 在 Python 中是一个对象)。这通常是 ORM 将空集映射到编程语言的方式。
EDIT:Gee, I just see that it's current_product.size
that's None
not current_product
. As said, I'm not familiar with Django's ORM, but this seems strange nevertheless: I'd either expect current_product
to be None
or size
having a numerical value.
编辑:哎呀,我刚才看到它current_product.size
说的None
不是current_product
。如前所述,我不熟悉 Django 的 ORM,但这似乎很奇怪:我要么期望current_product
是,None
要么size
有一个数值。