Reputation: 1127
In Django I use manage.py makemigrations
and manage.py migrate
on the following models.py file:
class Family(models.Model):
comment1 = models.CharField(max_length=80)
#comment2 = models.CharField(max_length=80)
After this successful initialization, I changed models.py to (I just uncomment the new model field which is basically a copy of the other model field):
class Family(models.Model):
comment1 = models.CharField(max_length=80)
comment2 = models.CharField(max_length=80)
Now when I try to makemigrations
again I get the following error:
You are trying to add a non-nullable field 'comment' to family 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 with a null value for this column)
2) Quit, and let me add a default in models.py Select an option:
Why didn't I get this error upon intialization in the first place?
Upvotes: 4
Views: 9236
Reputation: 1
Just select option 1
. Then set a default.
It will create a migration script with the property preserve_default=False
which means the default is used only for the migration. It will not affect the default settings in the database.
https://docs.djangoproject.com/en/4.2/ref/migration-operations/#alterfield
Upvotes: 0
Reputation: 1
You can add this: default=None
or default="something"
or add null=True
, blank=True
.
Upvotes: -1
Reputation: 610
I have faced a same issue, in my case:
Focus on the alert:
...non-nullable field 'comment' to family...
Just add one more attr in the field comment of the model family:
default=''
Upvotes: 0
Reputation: 31
image1=models.ImageField(upload_to='app/image12',help_text="hi", null=True)
That is, set null= True'
in the field.
It happens when you change your model after stored database.
Upvotes: 3
Reputation: 11073
Others are right. you should set a default value for that field.
but there is a a trick that you can solve this. but it is not a good way... only if you have no choice.
1. comment all of your table
2. run makemigrations
and migrate
3. uncomment your table
4.2. run makemigrations
and migrate
again
Upvotes: 3
Reputation: 166
If you want to make it non nullable without default. you have to provide value for the same field when you create migration file. thats why it asks for the option. type "1" in terminal while python manage.py makemigrations and then provide a value for the field for previously saved row(if any).
Let me know if this helps.
Upvotes: 0