Vicky Leong
Vicky Leong

Reputation: 1258

How to delete ForeignKey field from model safely?

I have a model like this (simplified for relevancy):

class Director(models.Model):

    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    user_account = models.ForeignKey(User, null=True, blank=True)

I just realized that user_account needs to be OneToOneField instead of ForeignKey. Making that change will essentially mean removing the existing user_account field and creating the new one.

The problem is that I had bad experience in the past when messing with ForeignKey field. To make matters worse, I already created a couple of Director objects in the database with the ForeignKey linked to User objects.

My question is how can I delete, and ultimately change, user_account field without causing runtime errors later on?

Additional context: I'm using Django 1.9 and PostgreSQL.

Upvotes: 3

Views: 2120

Answers (3)

chiseledCoder
chiseledCoder

Reputation: 385

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.

Upvotes: 1

Alasdair
Alasdair

Reputation: 308809

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.

Upvotes: 2

Shang Wang
Shang Wang

Reputation: 25539

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.

Upvotes: 1

Related Questions