user3475724
user3475724

Reputation:

Empty CharField with null=True returns NoneType Django 1.8

As fas as I understand, this CharField must return null when it's not filled with data, but instead it returns None.

  number_of_likes = models.CharField(max_length=1000, blank=False, null=True)

The main issue for me is when I want to incriminate previous value, I get such sort of problem

int() argument must be a string, a bytes-like object or a number, not 'NoneType'

How should I handle it?

object.number_of_likes = previus_number_of_likes  + 1

Upvotes: 1

Views: 752

Answers (3)

SarathKumar95
SarathKumar95

Reputation: 1

null may not have public availabilty but exists as a property when using models.Integerfield although Django docs has explicitly said that it is best to avoid using it with Charfield - https://docs.djangoproject.com/en/4.0/ref/models/fields/

Upvotes: 0

damores
damores

Reputation: 2351

As others have pointed out, null doesn't exist in python, None is the way to represent null values. That said, there are several ways you could address your issue:

Option 1: Change your field definition to:

 number_of_likes = models.IntegerField(default=0)

Option 2: If you don't want to change the field, you could:

 object.number_of_likes = int(object.number_of_likes) + 1 if object.number_of_likes else 1

Hope this helps

Upvotes: 2

pragman
pragman

Reputation: 1644

Just to check I did a python manage.py shell and typed

>>> null

and got:

NameError: name 'null' is not defined

I don't think there's a null, except when a None is stored into the database.

Upvotes: 0

Related Questions