Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Django model parent class to existing an existing model for multi-table inheritance

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?

like image 727
Ryan Allen Avatar asked Mar 12 '23 10:03

Ryan Allen


1 Answers

  1. Add the new models but keep the old one as well. Make migrations.

  2. Write a custom migration to copy the data from the Restaurant model to the NewRestaurant model.

  3. If necessary, change over any foreign key fields in other models from Restaurant to NewRestaurant and make migrations.

  4. If necessary, change everywhere in the app that the Restaurant class is used to use the NewRestaurant class.

  5. Delete the old restaurant model and make migrations.

  6. Rename the new restaurant model to Restaurant so everything works again with the new structure. Make migrations.

like image 164
Ryan Allen Avatar answered Mar 14 '23 23:03

Ryan Allen