[Django]-How to delete ForeignKey field from model safely?

1πŸ‘

βœ…

I think you can use django migrations to do that.

  1. Add a OneToOne field pointing to the model User, you might need to add related_name for that.

  2. Create one migration that apply the field to database.

  3. Create a data migration and copy the ForeignKey value from user_account to the new field for each Director.

  4. Delete your user_account field in model, then create another migration to apply the deletion to the database.

πŸ‘€Shang Wang

2πŸ‘

ForeignKey and OneToOneField are the same, except OneToOneField has a unique constraint. Try changing the field in your models and running makemigrations β€” I think Django should be smart enough to be able to create the required migration.

Before you start, you need to make sure that there aren’t multiple director instances pointing to the same user, because this isn’t allowed by a one to one field.

πŸ‘€Alasdair

1πŸ‘

There is not much difference between ForeignKey and OneToOneField. If you run directly change the model field type, your data will not be disturbed. After changing the model field type, run makemigrations.

πŸ‘€chiseledCoder

Leave a comment