Reputation: 4515
This is an extension to this question: How to move a model between two Django apps (Django 1.7)
I want to move a model M from an app A to app B using Django migrations without losing data. The best voted answer to the question (not the accepted one, the one by ozan) suggested usage of migrations.SeparateDatabaseAndState and doing it in two steps:
This looks like a very clever way to me, however in my case there is another model N that has a foreign key to M. Now, when I call makemigrations to make the migration file in step two, I get an error because at that stage model A.M does no more exist:
ValueError: Lookup failed for model referenced by field C.N.m: A.M
Is there a way to handle this?
Upvotes: 4
Views: 1874
Reputation: 4515
This is how I finally did it. The main idea is doing the creation of the new model before the deletion of the old one as schillingt suggested, but also using migrations.SeparateDatabaseAndState to avoid database modifications as in the linked question.
Copy the model from A to B. Define db_table to assign the same table name
Make migrations for B. Modify the migration file to only create the state not the database table using migrations.SeparateDatabaseAndState.
Modify the foreign key in N to point to B.M instead of A.M (via to='B.M').
Make migration for this change.
Delete model from A.
Make migration for the deletion. Modify it such that it only deletes the model, not the database table.
Apply all migrations.
One could still rename the table afterwards, however in the version 1.7 I use, migrations do not support db_table changes.
Upvotes: 6
Reputation: 13731
Here's how I would handle it.
Upvotes: 1