pythondjangodjango-modelsdjango-rest-frameworkdjango-views

It is impossible to add a non-nullable field 'name' to table_name without specifying a default


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?


Solution

  • 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