Django 1.7 blank CharField/TextField convention
Solution 1
It's not a bug, it's documented and logical.
You add a new field, which is (by best practice, as you noticed) not NULL
able so django has to put something into it for the existing records - I guess you want it to be the empty string.
you can
1) Provide a one-off default now (will be set on all existing rows)
so just press 1, and provide ''
(the empty string) as value.
or specify default=''
in the models.py, as suggested:
2) Quit, and let me add a default in models.py
Solution 2
- select 1 ,it will through to python terminal.
- Give timezone.now(), it will exit from python terminal.
Note:it may not exit from terminal at first time,give that command once again.
Jeremy Swinarton
Updated on May 17, 2020Comments
-
Jeremy Swinarton about 4 years
Using Django's new migration framework, 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)
I now 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 this 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
tofield_2
, but Django's convention is to avoid using null on string-based fields like CharField and TextField (from https://docs.djangoproject.com/en/dev/ref/models/fields/). Is this a bug, or am I misunderstanding the docs? -
Jeremy Swinarton over 9 yearsI guess that makes sense, but it strikes me as odd behaviour. I expect that if I specify
blank=True
, the migration will automatically use a blank string as the default, the same way that if I specifynull=True
, I don't need to tell the migration to useNULL
as the default. -
ch3ka over 9 yearsWell,
explicit is better than implicit
.blank=True
only tells the django admin to accept the empty string as input, it does not imply a default value.default=
does, and it's perfectly reasonable to specify a default value different from empty string. Fornull=True
, the migration does not useNULL
as default, but simply nothing - which happens to "evaluate" toNULL
.