Date Modified Tags python / django

Moving a Django model to another app can be tricky. Here is a quick rundown of the most convenient way I found so far. The idea is to simply rename the database tables, and force Django to consider this the new state of your models. Thanks to Marten Kenbeek who pointed me at SeparateDatabaseAndState.

This is probably still missing some edge cases and I only tested it on one project, so be careful.

  1. Create a backup.
  2. Copy the model code to the new app. Update any foreign key references as necessary.
  3. Run manage.py makemigrations new_app
  4. Edit the migration:
operations=[
    migrations.SeparateDatabaseAndState(
        database_operations=None,
        state_operations=[
            # Copy the auto-generated operations here.
        ],
    ),
],
  1. Delete the models from the old app.
  2. Run manage.py makemigrations old_app
  3. Edit the migration:
operations = [
    migrations.SeparateDatabaseAndState(
        database_operations=[
            migrations.AlterModelTable('mymodel', 'new_app_mymodel'),
            # Repeat for the other models you want to move.
        ],
        state_operations=[
            # Copy the auto-generated operations here.
        ],
    ),
],
  1. manage.py migrate