Django Model returning NoneType
12,709
Solution 1
NoneType
is the type that the None
value has. You want to change the second snippet to
if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
Solution 2
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:
if someobject.someattr is None:
# Not set yet
Author by
fishu
Updated on June 04, 2022Comments
-
fishu almost 2 years
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()
What is NoneType and how can I test for it?
-
fishu over 15 yearsCheers, I thought I'd tried that. That's why I was trying testing the length. Ah well. You get this on the big jobs
-
Ferdinand Beyer over 15 yearsIn fact, Django will raise an exception in this case (Product.NotFound).
-
Ignacio Vazquez-Abrams over 15 yearsCalling it "undefined" is a bit facetious. The variable/name is defined, but it has no useful value.
-
ruds over 15 yearsYou do at that. I like this idiom -- it eliminates an "or" that makes the code less readable, and that's easy to forget (as illustrated here :) )
-
user1066101 over 15 yearsPlease use "is not None" rather than assuming that None is like False -- it make the if statement perfectly clear.
-
Carl Meyer over 15 years@S.Lott: I don't see any reason to test for None specifically in this case. The purpose is to test whether current_product.size has any contents, and this does that more clearly than a complicated double-check for "is not None" and len().
-
ruds over 15 years@Carl Meyer: Exactly. "is not None" is the correct idiom when you're testing for None-ness, but if you're checking whether a list is both non-None and has contents, use the list as a boolean value.