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
Restaurantmodel to theNewRestaurantmodel.If necessary, change over any foreign key fields in other models from
RestauranttoNewRestaurantand make migrations.If necessary, change everywhere in the app that the
Restaurantclass is used to use theNewRestaurantclass.Delete the old restaurant model and make migrations.
Rename the new restaurant model to
Restaurantso everything works again with the new structure. Make migrations.