[Django]-How can I resolve the Django error "add a non-nullable field"?

6👍

Your code isn’t wrong. Just follow the instructions provided by the message…

The person field within your Operator model can’t be null (because null=True isn’t set). You must already have Operators in your database, so Django doesn’t know what to do with those.

You need to either: (a) provide a default value in your model, (b) provide a default during the migration process, or (c) enable null values for that field.

0👍

If you don’t want to have null=True property in your model or set a FK instance manually which isn’t a simple task sometimes, you can do the following:

  1. Delete all instances of Person and Operator models from your DB (e.g. using DjangoAdmin).
  2. Set null=True of the FK field of your child model (field person of model Operator in your case).
  3. Run python manage.py makemigrations.
  4. Delete null=True property from p. 2.
  5. Run python manage.py makemigrations again.
  6. When running makemigrations from p. 5, you need to choose 2) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation.
  7. Run python manage.py migrate.

The main downside of the method is that you have to delete all instances of at least two your models which isn’t always acceptable. However, I’m sure if it isn’t your case, this is the best way to solve the error.

Leave a comment