I am in a situation where I need to do some changes to my models and I’d like to come up with the best way to make those changes without losing data on a database with existing data.
This is my current scheme:
class Main(models.Model): oto_a = OneToOneField(A) oto_b = OneToOne(B) class A(models.Model): field_1 = ... field_2 = ... class B(models.Model): field_3 = ... field_4 = ... class A_child(models.Model): father = models.ForeignKey(A) field_c1 = ... field_c2 = ... class B_child(models.Model): father = models.ForeignKey(B) field_c3 = ... field_c4 = ...
These models form sort of a tree: for every instance of
Main, there’s exactly one of each
B. Moreover, for each
A_child there’s a
B_child: those are like siblings, and there’s a de facto one-to-one relationship between those as well.
What I’d like to do now, is to migrate to the following scheme:
class Main(models.Model): field_1 = ... field_2 = ... field_3 = ... field_4 = ... class MainChild(models.Model): father = ForeignKey(Main) field_c1 = ... field_c2 = ... field_c3 = ... field_c4 = ...
In other words, I want to resolve the one-to-one relationships into single models, as well as remove the level of indirection introduced by the models
B and have the “merged” child class reference model
What I’m trying to do is accomplish this without losing any data from the existing models. In other words, I want to get all the
Main instances, copy the data from their former
B related, then for the two latter models I want to walk their children and create a
MainChild for each of them and copy the values of their fields into them.
Is there a best way to do this?
I have an idea that I’m not 100% confident of, which is the following:
- I create all the new fields I need inside of
Main, but don’t remove the one-to-one fields. Then I create the
- I iterate over all the instances of
Main, access their
Band copy their values into the newly created fields in
Main. Then I iterate through all their children and create a
MainChild, then copy the fields of the children combined into the new child
- I delete the one-to-one fields in
Do better ways come to mind to you? Thank you.