Django change model, migrate, and update the existing records

Viewed 719

I had a Django model defined as:

from users.models import User

class Record(models.Model):
  user = models.ForeignKey(
            User,
            on_delete=SET_NULL,
            null=True)
  ...

I realized that it would be better to rewrite the above model as:

from userprofile.models import UserProfile

class Record(models.Model):
  user = models.ForeignKey(
            UserProfile,
            on_delete=SET_NULL,
            null=True)
  ....

How can I migrate (so the new definition of the model Record) is used, without having to lose the old Record instances in the databases? What is the general process of such migrations? Because if I migrate with the new definition of Record, I lose access to the old Record objects so I can't update them. However, if I don't migrate, Django won't let me use UserProfile as the user field.

1 Answers

There is nothing to migrate in this way, as user is a Python attribute and there is no backing db column since it is not defined as ForeignKey.

In that case Django will handle this automatically, as it will discover the change of name for the model and it will alter the table name on DB side, then it will update the referencing table for Record table.

you can run python manage.py makemigrations and see the generated migrations.

Related