Solomon
Solomon

Reputation: 298

How can I completely alter my Django database schema without losing any data?

I'm making some big changes to the schema of my database, but I don't want to lose any data in the process of migrating to the new schema. Let me provide a specific example. I currently have a class Person(models.Model), and each Person instance has a bunch of data associated with it like a name, age, etc. There are already many Person instances in my database. I now realize that I actually need two types of Person, a Student and a Teacher, and each of those types will have their own unique variables and methods. It seems to me that the best way to accomplish this is by making Person an abstract class and making Student and Teacher extend that class. Some of variables in Person currently only apply to Student, so I want to move those variables into the Student subclass.

In general, how could I go about doing this migration without losing any data? I'm fairly new to Django, so I don't really know where to start except that I probably need to write some kind of custom script to be run with python manage.py.

Upvotes: 0

Views: 1136

Answers (1)

Ryan W
Ryan W

Reputation: 131

What you're looking for is Django data migrations.

  1. Add abstract = True to you person meta model
  2. Add your Student and Teacher models and have them inherit from Person
  3. run manage.py makemigrations
  4. The resulting migration will have operations that add your new models and remove Person. Your custom data migration operation needs to come after the creation and before the delete. Follow the Django docs example that migrates the name field on the Person model but instead, create instances of the new Student and Teacher models for each person. Be sure to save the new instances.

Other tips:

  1. Use fixtures to backup your data so that you can easily restore it in the event you make a mistake during migration
  2. It would be prudent to rename your new special migration to make it more easily identifiable by you in the future

Upvotes: 3

Related Questions