[Django]-Django Model returning NoneType

8👍

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
👤ruds

1👍

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

0👍

I can best explain the NoneType error with this example of erroneous code:

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

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

-1👍

I don’t know Django, but I assume that some kind of ORM is involved when you do this:

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.

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.

Leave a comment