Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: non-nullable field without a default

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?

like image 341
user3182532 Avatar asked Oct 28 '25 04:10

user3182532


2 Answers

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

like image 108
Mehrdad Pedramfar Avatar answered Oct 29 '25 17:10

Mehrdad Pedramfar


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.

like image 38
arpit shukla Avatar answered Oct 29 '25 18:10

arpit shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!