Django: It is impossible to add a non-nullable field without specifying a default.

django
Category Software and digital electronics / Coding
2024-08-24 05:14

I defined new row location inside Django model Shop as follows:

class Shop(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)

When trying to migration via

python3 manage.py makemigrations

, I receive this output response in command-line:

It is impossible to add a non-nullable field 'location' to shop 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.
Select an option:

How can I fix this without making the field nullable?

I want an empty entry being defined and the model links there.

Answered by robin
2024-08-24 12:09

You should set the default value at the field definition as follows:

location = models.ForeignKey(Location, on_delete=models.CASCADE, default=Location.objects.first().pk)
×

Login

No account?
Terms of use
Forgot password?