Writing database migrations

This document explains how to structure and write database migrations for different scenarios you might encounter. For introductory material on migrations, see the topic guide.

Data migrations and multiple databases

When using multiple databases, you may need to figure out whether or not to run a migration against a particular database. For example, you may want to only run a migration on a particular database.

In order to do that you can check the database connection’s alias inside a RunPython operation by looking at the schema_editor.connection.alias attribute:

  1. from django.db import migrations
  2. def forwards(apps, schema_editor):
  3. if schema_editor.connection.alias != 'default':
  4. return
  5. # Your migration code goes here
  6. class Migration(migrations.Migration):
  7. dependencies = [
  8. # Dependencies to other migrations
  9. ]
  10. operations = [
  11. migrations.RunPython(forwards),
  12. ]

You can also provide hints that will be passed to the allow_migrate() method of database routers as **hints:

myapp/dbrouters.py

  1. class MyRouter:
  2. def allow_migrate(self, db, app_label, model_name=None, **hints):
  3. if 'target_db' in hints:
  4. return db == hints['target_db']
  5. return True

Then, to leverage this in your migrations, do the following:

  1. from django.db import migrations
  2. def forwards(apps, schema_editor):
  3. # Your migration code goes here
  4. ...
  5. class Migration(migrations.Migration):
  6. dependencies = [
  7. # Dependencies to other migrations
  8. ]
  9. operations = [
  10. migrations.RunPython(forwards, hints={'target_db': 'default'}),
  11. ]

If your RunPython or RunSQL operation only affects one model, it’s good practice to pass model_name as a hint to make it as transparent as possible to the router. This is especially important for reusable and third-party apps.

Migrations that add unique fields

Applying a “plain” migration that adds a unique non-nullable field to a table with existing rows will raise an error because the value used to populate existing rows is generated only once, thus breaking the unique constraint.

Therefore, the following steps should be taken. In this example, we’ll add a non-nullable UUIDField with a default value. Modify the respective field according to your needs.

  • Add the field on your model with default=uuid.uuid4 and unique=True arguments (choose an appropriate default for the type of the field you’re adding).

  • Run the makemigrations command. This should generate a migration with an AddField operation.

  • Generate two empty migration files for the same app by running makemigrations myapp --empty twice. We’ve renamed the migration files to give them meaningful names in the examples below.

  • Copy the AddField operation from the auto-generated migration (the first of the three new files) to the last migration, change AddField to AlterField, and add imports of uuid and models. For example:

    0006_remove_uuid_null.py

    1. # Generated by Django A.B on YYYY-MM-DD HH:MM
    2. from django.db import migrations, models
    3. import uuid
    4. class Migration(migrations.Migration):
    5. dependencies = [
    6. ('myapp', '0005_populate_uuid_values'),
    7. ]
    8. operations = [
    9. migrations.AlterField(
    10. model_name='mymodel',
    11. name='uuid',
    12. field=models.UUIDField(default=uuid.uuid4, unique=True),
    13. ),
    14. ]
  • Edit the first migration file. The generated migration class should look similar to this:

    0004_add_uuid_field.py

    1. class Migration(migrations.Migration):
    2. dependencies = [
    3. ('myapp', '0003_auto_20150129_1705'),
    4. ]
    5. operations = [
    6. migrations.AddField(
    7. model_name='mymodel',
    8. name='uuid',
    9. field=models.UUIDField(default=uuid.uuid4, unique=True),
    10. ),
    11. ]

    Change unique=True to null=True – this will create the intermediary null field and defer creating the unique constraint until we’ve populated unique values on all the rows.

  • In the first empty migration file, add a RunPython or RunSQL operation to generate a unique value (UUID in the example) for each existing row. Also add an import of uuid. For example:

    0005_populate_uuid_values.py

    1. # Generated by Django A.B on YYYY-MM-DD HH:MM
    2. from django.db import migrations
    3. import uuid
    4. def gen_uuid(apps, schema_editor):
    5. MyModel = apps.get_model('myapp', 'MyModel')
    6. for row in MyModel.objects.all():
    7. row.uuid = uuid.uuid4()
    8. row.save(update_fields=['uuid'])
    9. class Migration(migrations.Migration):
    10. dependencies = [
    11. ('myapp', '0004_add_uuid_field'),
    12. ]
    13. operations = [
    14. # omit reverse_code=... if you don't want the migration to be reversible.
    15. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    16. ]
  • Now you can apply the migrations as usual with the migrate command.

    Note there is a race condition if you allow objects to be created while this migration is running. Objects created after the AddField and before RunPython will have their original uuid’s overwritten.

Non-atomic migrations

On databases that support DDL transactions (SQLite and PostgreSQL), migrations will run inside a transaction by default. For use cases such as performing data migrations on large tables, you may want to prevent a migration from running in a transaction by setting the atomic attribute to False:

  1. from django.db import migrations
  2. class Migration(migrations.Migration):
  3. atomic = False

Within such a migration, all operations are run without a transaction. It’s possible to execute parts of the migration inside a transaction using atomic() or by passing atomic=True to RunPython.

Here’s an example of a non-atomic data migration that updates a large table in smaller batches:

  1. import uuid
  2. from django.db import migrations, transaction
  3. def gen_uuid(apps, schema_editor):
  4. MyModel = apps.get_model('myapp', 'MyModel')
  5. while MyModel.objects.filter(uuid__isnull=True).exists():
  6. with transaction.atomic():
  7. for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:
  8. row.uuid = uuid.uuid4()
  9. row.save()
  10. class Migration(migrations.Migration):
  11. atomic = False
  12. operations = [
  13. migrations.RunPython(gen_uuid),
  14. ]

The atomic attribute doesn’t have an effect on databases that don’t support DDL transactions (e.g. MySQL, Oracle). (MySQL’s atomic DDL statement support refers to individual statements rather than multiple statements wrapped in a transaction that can be rolled back.)

Controlling the order of migrations

Django determines the order in which migrations should be applied not by the filename of each migration, but by building a graph using two properties on the Migration class: dependencies and run_before.

If you’ve used the makemigrations command you’ve probably already seen dependencies in action because auto-created migrations have this defined as part of their creation process.

The dependencies property is declared like this:

  1. from django.db import migrations
  2. class Migration(migrations.Migration):
  3. dependencies = [
  4. ('myapp', '0123_the_previous_migration'),
  5. ]

Usually this will be enough, but from time to time you may need to ensure that your migration runs before other migrations. This is useful, for example, to make third-party apps’ migrations run after your AUTH_USER_MODEL replacement.

To achieve this, place all migrations that should depend on yours in the run_before attribute on your Migration class:

  1. class Migration(migrations.Migration):
  2. ...
  3. run_before = [
  4. ('third_party_app', '0001_do_awesome'),
  5. ]

Prefer using dependencies over run_before when possible. You should only use run_before if it is undesirable or impractical to specify dependencies in the migration which you want to run after the one you are writing.

Migrating data between third-party apps

You can use a data migration to move data from one third-party application to another.

If you plan to remove the old app later, you’ll need to set the dependencies property based on whether or not the old app is installed. Otherwise, you’ll have missing dependencies once you uninstall the old app. Similarly, you’ll need to catch LookupError in the apps.get_model() call that retrieves models from the old app. This approach allows you to deploy your project anywhere without first installing and then uninstalling the old app.

Here’s a sample migration:

myapp/migrations/0124_move_old_app_to_new_app.py

  1. from django.apps import apps as global_apps
  2. from django.db import migrations
  3. def forwards(apps, schema_editor):
  4. try:
  5. OldModel = apps.get_model('old_app', 'OldModel')
  6. except LookupError:
  7. # The old app isn't installed.
  8. return
  9. NewModel = apps.get_model('new_app', 'NewModel')
  10. NewModel.objects.bulk_create(
  11. NewModel(new_attribute=old_object.old_attribute)
  12. for old_object in OldModel.objects.all()
  13. )
  14. class Migration(migrations.Migration):
  15. operations = [
  16. migrations.RunPython(forwards, migrations.RunPython.noop),
  17. ]
  18. dependencies = [
  19. ('myapp', '0123_the_previous_migration'),
  20. ('new_app', '0001_initial'),
  21. ]
  22. if global_apps.is_installed('old_app'):
  23. dependencies.append(('old_app', '0001_initial'))

Also consider what you want to happen when the migration is unapplied. You could either do nothing (as in the example above) or remove some or all of the data from the new application. Adjust the second argument of the RunPython operation accordingly.

Changing a ManyToManyField to use a through model

If you change a ManyToManyField to use a through model, the default migration will delete the existing table and create a new one, losing the existing relations. To avoid this, you can use SeparateDatabaseAndState to rename the existing table to the new table name while telling the migration autodetector that the new model has been created. You can check the existing table name through sqlmigrate or dbshell. You can check the new table name with the through model’s _meta.db_table property. Your new through model should use the same names for the ForeignKeys as Django did. Also if it needs any extra fields, they should be added in operations after SeparateDatabaseAndState.

For example, if we had a Book model with a ManyToManyField linking to Author, we could add a through model AuthorBook with a new field is_primary, like so:

  1. from django.db import migrations, models
  2. import django.db.models.deletion
  3. class Migration(migrations.Migration):
  4. dependencies = [
  5. ('core', '0001_initial'),
  6. ]
  7. operations = [
  8. migrations.SeparateDatabaseAndState(
  9. database_operations=[
  10. # Old table name from checking with sqlmigrate, new table
  11. # name from AuthorBook._meta.db_table.
  12. migrations.RunSQL(
  13. sql='ALTER TABLE core_book_authors RENAME TO core_authorbook',
  14. reverse_sql='ALTER TABLE core_authorbook RENAME TO core_book_authors',
  15. ),
  16. ],
  17. state_operations=[
  18. migrations.CreateModel(
  19. name='AuthorBook',
  20. fields=[
  21. (
  22. 'id',
  23. models.AutoField(
  24. auto_created=True,
  25. primary_key=True,
  26. serialize=False,
  27. verbose_name='ID',
  28. ),
  29. ),
  30. (
  31. 'author',
  32. models.ForeignKey(
  33. on_delete=django.db.models.deletion.DO_NOTHING,
  34. to='core.Author',
  35. ),
  36. ),
  37. (
  38. 'book',
  39. models.ForeignKey(
  40. on_delete=django.db.models.deletion.DO_NOTHING,
  41. to='core.Book',
  42. ),
  43. ),
  44. ],
  45. ),
  46. migrations.AlterField(
  47. model_name='book',
  48. name='authors',
  49. field=models.ManyToManyField(
  50. to='core.Author',
  51. through='core.AuthorBook',
  52. ),
  53. ),
  54. ],
  55. ),
  56. migrations.AddField(
  57. model_name='authorbook',
  58. name='is_primary',
  59. field=models.BooleanField(default=False),
  60. ),
  61. ]

Changing an unmanaged model to managed

If you want to change an unmanaged model (managed=False) to managed, you must remove managed=False and generate a migration before making other schema-related changes to the model, since schema changes that appear in the migration that contains the operation to change Meta.managed may not be applied.