The Django Docs uses this example to demonstrate multi-table inheritance:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
If I had initially built the Restaurant class like so:
class Restaurant(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
and then after a bunch of Restaurant objects have already been created, I realize it would have been better to use MTI, is there a good way to create the parent Place class after the fact and migrate the data?
Add the new models but keep the old one as well. Make migrations.
Write a custom migration to copy the data from the
Restaurant
model to theNewRestaurant
model.If necessary, change over any foreign key fields in other models from
Restaurant
toNewRestaurant
and make migrations.If necessary, change everywhere in the app that the
Restaurant
class is used to use theNewRestaurant
class.Delete the old restaurant model and make migrations.
Rename the new restaurant model to
Restaurant
so everything works again with the new structure. Make migrations.