2

I have an 'address' field in my Django model that I want to be optional:

class Home(models.Model):
    address = models.CharField(max_length=256, blank=True, default=None)
    city = models.CharField(max_length=25)

I want this to be an optional field in my database but I didn't set "null=True" because the documentation says

"Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL."

However, when I create a Home object with this command:

Home.objects.create(city='Chicago')

I get an error:

IntegrityError: null value in column 'address' violates not-null constraint.

Shouldn't I add "null=True" to the address field despite what the docs say in order to make it optional? If not, how should it be declared so that I can create new Home objects without raising this error?

Jim
  • 13,430
  • 26
  • 104
  • 155

2 Answers2

5

You should get rid of default=None, otherwise, you can just use default=''

Hybrid
  • 6,741
  • 3
  • 25
  • 45
  • I think that this is the best way to do it, because it is consistent with how Django represents empty CharFields. – souldeux Dec 06 '16 at 20:06
  • When I make this change and examine my PostgreSQL database table schema, it still says that the address field is "not null". – Jim Dec 06 '16 at 22:38
  • Did you run 'manage.py makemigrations' and 'manage.py migrate'? – Hybrid Dec 06 '16 at 22:39
  • Ok great, but is this new issue an error, or it just says the field is not null? – Hybrid Dec 06 '16 at 22:51
  • When doing \d, the database schema just says that the address field is "not null" It's not a database error. – Jim Dec 06 '16 at 23:07
  • Sounds like it's working - `not null` would make sense, considering that `default=''` is an empty string (and therefor not null) – Hybrid Dec 06 '16 at 23:07
0

if you not always add address you need to add

null= True 

because default is set to None but the DB isn't set to accept null's

Tal.S
  • 113
  • 1
  • 7
  • I don't understand why the documentation says what it does without addressing this issue so I'm just going to set "null=True" as I usually do. – Jim Dec 07 '16 at 00:05