Skip to content

Migrating data models

Gustavo Silva edited this page Feb 10, 2023 · 1 revision

Migrating models

When migrating models that were already in production, please ensure no data is lost in the process and that old permissions do not stick around when no longer needed. The best way to achieve this is by going through the following steps:

  1. Copy the existing models to the new location. Adjust foreign keys as needed. (for reference, check this SO's question)
  2. Create an empty migration in the old app (python manage.py makemigrations old_app --empty) and write the migration so that it moves the models to the new location and deletes the old model. These should be split into database_operations and state_operations.
  3. Create a new migration in the new location (python manage.py makemigrations new_location) and ensure you use the migration_helpers to move the permissions and the delete the old ones. To do that, in the that new migration, you should create a snippet similar to the following:
import django.db.models.deletion
from django.db import migrations, models
from surface.migration_helpers.perms import migrate_perms


def handle_perms(apps, schema_editor):
    list_changed_models = [
        ("oldapp_model", "newapp_model"),
        ("oldapp_anothermodel", "newapp_anothermodel"),
        # and as many as you have in hands
    ]

    migrate_perms(apps=apps, list_models=list_changed_models)


class Migration(migrations.Migration):
    # set your dependencies right
    # make sure you add this custom operation in the list of operations:

    operations = [
        # ...
        migrations.RunPython(handle_perms),
        # ...
    ]

After running the migrations and seeing no errors, ensure you can run the test suite successfully and that things are working as expected.