Home > Enterprise >  It is impossible to add a non-nullable field 'name' to table_name without specifying a def
It is impossible to add a non-nullable field 'name' to table_name without specifying a def

Time:01-16

I have added a following field in my already existing model:

name = models.CharField(max_length=128, unique=True)

But it is giving following prompt when applying migrations:

 It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because 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 manually define a default value in models.py.

I cannot set it's attributes to blank=True, null=True as this field is must. I cannot set it's default value as the field has to be unique. I also deleted all the previous data from that table. If I try to set it's default value in command prompt, it says plz select a valid option. How to fix it?

CodePudding user response:

The issue is that you probably have existing records, but this field is new and unique.

This is what I suggest to do:

  1. Use blank=True, null=True
  2. Fill the existing records with unique names using data migration or manually.
  3. Remove blank=True and null=True in next migration

CodePudding user response:

It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because 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 manually define a default value in models.py.

Solution: Select option 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) for now and then go to your models and make these changes: name = models.CharField(max_length=128, blank=True) Note* : you must remove name(unique = True) because blank names will not be unique and for uniquiness use id as a primary key

  • Related