Hi gang,
I'm trying to refactor the apps in my project, and I can't figure out any clean way to migrate models with their data from one app to another. I'm really looking for answers to two questions:
1. Is there any canonical way to do this?
2. I've moved my models to the new app but I have them using the tables from the old app using Meta.db_table. How do I make migrations understand what's going on and not try to delete my old tables? Once migrations gets what's going on, how do I rename the old table so it fits the new app name so I no longer need Meta.db_table?
--
For question 1. I'm really surprised there isn't a good way to do this. I mean—this is kind of a blatant use case for a migration—moving a model from one app to another.
My initial thought was to use a use a three phase migration. Create new models, copy data over, delete old models. But I'd really rather not 'cause the models are all very interconnected and that seems like a recipe for a foreign key disaster.
What I actually went with was to move all the models over to the new app, and then point them at the old tables using Meta.db_table. Everything works, but when I run makemigrations it is confused as crap and wants to destroy everything, which brings me to question 2...
---
So question 2, now that I have my model code in a new app pointing at the old tables, how do I get the tables renamed to use canonical table names and let migrations know wtf is going on?
With the current situation, if I run makemigrations it does something like this
Migrations for 'new_app':
- Add field contact to building
Migrations for 'old_app':
0006_auto_delete_blah.py:
- Remove field contact from building
...
all of which is roughly correct, just doesn't keep my data intact. :P
My gameplan (please correct me if any of this is wrong) is to:
1. Fake the ('new_app', '0001_initial') migration.
2. Make a new data migration depending on ('new_app', '0001_initial') and the ('old_app', '0005_...') that uses AlterModelTable to rename the tables to their canonical names as would normally be created by the 0001_initial migration. 3. Fake the ('old_app', '0006_auto_delete_blah')migration.
4. Get rid of the Meta.db_table entries so my moved models just use the normal table names they're supposed to.
Seems like it should get me to where I want to go.
Am I smoking crack? Is this really that hard?
Thanks!
Andy.