Django 1.7 empty CharField / TextField

Using the new Django migration infrastructure, let's say I have the following model that already exists in the database:

class TestModel(models.Model): field_1 = models.CharField(max_length=20) 

Now I want to add a new TextField to the model, so it looks like this:

 class TestModel(models.Model): field_1 = models.CharField(max_length=20) field_2 = models.TextField(blank=True) 

When I try to migrate this model using python manage.py makemigrations , I get the following prompt:

 You are trying to add a non-nullable field 'field_2' to testmodel without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py 

I can easily fix this by adding null=True to field_2 , but the Django convention should avoid using a null value in string methods like CharField and TextField (from https://docs.djangoproject.com/en/dev/ref/models/ fields / ). Is this a mistake, or do I not understand the documents?

+6
source share
2 answers

This is not a mistake; it is documented and logical. You are adding a new field which (as best practice, as you have noticed) is not NULL , so django should insert something into it for existing records - I think you want it to be an empty string.

You can

  1) Provide a one-off default now (will be set on all existing rows) 

so just press 1 and specify '' (empty string) as the value.

or specify default='' in models.py as suggested:

  2) Quit, and let me add a default in models.py 
+25
source
  1. select 1, it will be through the Python terminal.
  2. Give timezone.now (), it will exit the Python terminal.

Note: it cannot exit the terminal for the first time, issue this command again.

0
source

Source: https://habr.com/ru/post/1206103/


All Articles