Writing database migrations

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

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

    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.  
    3. def allow_migrate(self, db, app_label, model_name=None, **hints):
    4. if 'target_db' in hints:
    5. return db == hints['target_db']
    6. return True

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

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

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

    Applying a "plain" migration that adds a unique non-nullable field to a tablewith existing rows will raise an error because the value used to populateexisting rows is generated only once, thus breaking the unique constraint.

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

    • Add the field on your model with default=uuid.uuid4 and unique=Truearguments (choose an appropriate default for the type of the field you'readding).

    • Run the command. This should generate a migrationwith an AddField operation.

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

    0006_remove_uuid_null.py

    • Edit the first migration file. The generated migration class should looksimilar to this:

    0004_add_uuid_field.py

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

    Change unique=True to null=True — this will create the intermediarynull field and defer creating the unique constraint until we've populatedunique values on all the rows.

    • In the first empty migration file, add aRunPython or operation to generate aunique value (UUID in the example) for each existing row. Also add an importof 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.  
    5. def gen_uuid(apps, schema_editor):
    6. MyModel = apps.get_model('myapp', 'MyModel')
    7. for row in MyModel.objects.all():
    8. row.uuid = uuid.uuid4()
    9. row.save(update_fields=['uuid'])
    10.  
    11. class Migration(migrations.Migration):
    12.  
    13. dependencies = [
    14. ('myapp', '0004_add_uuid_field'),
    15. ]
    16.  
    17. operations = [
    18. # omit reverse_code=... if you don't want the migration to be reversible.
    19. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    20. ]
    • Now you can apply the migrations as usual with the command.

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

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

    Within such a migration, all operations are run without a transaction. It'spossible to execute parts of the migration inside a transaction usingatomic() or by passing atomic=True toRunPython.

    Here's an example of a non-atomic data migration that updates a large table insmaller batches:

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

    The attribute doesn't have an effect on databases that don't supportDDL transactions (e.g. MySQL, Oracle). (MySQL's refers to individualstatements rather than multiple statements wrapped in a transaction that can berolled back.)

    If you've used the makemigrations command you've probablyalready seen dependencies in action because auto-createdmigrations have this defined as part of their creation process.

    The dependencies property is declared like this:

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

    Usually this will be enough, but from time to time you may need toensure that your migration runs before other migrations. This isuseful, for example, to make third-party apps' migrations run _after_your replacement.

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

    Prefer using dependencies over run_before when possible. You shouldonly use run_before if it is undesirable or impractical to specifydependencies in the migration which you want to run after the one you arewriting.

    你可以使用数据迁移把数据从一个第三方应用程序中转移到另一个。

    如果你计划要移除旧应用程序,则需要根据是否安装旧应用程序来设置 依赖 属性。否则,一旦你卸载旧应用程序,就会缺失依赖项。同样,你需要在 app.get_model() 捕获 LookupError 来从旧应用程序中检索模型。这种途径允许你在任何地方部署项目,而无需先安装并且卸载旧应用程序。

    这是一个迁移示例:

    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.  
    4. def forwards(apps, schema_editor):
    5. try:
    6. OldModel = apps.get_model('old_app', 'OldModel')
    7. except LookupError:
    8. # The old app isn't installed.
    9. return
    10.  
    11. NewModel = apps.get_model('new_app', 'NewModel')
    12. NewModel.objects.bulk_create(
    13. NewModel(new_attribute=old_object.old_attribute)
    14. for old_object in OldModel.objects.all()
    15. )
    16.  
    17. class Migration(migrations.Migration):
    18. operations = [
    19. migrations.RunPython(forwards, migrations.RunPython.noop),
    20. ]
    21. dependencies = [
    22. ('myapp', '0123_the_previous_migration'),
    23. ('new_app', '0001_initial'),
    24. ]
    25.  
    26. if global_apps.is_installed('old_app'):
    27. dependencies.append(('old_app', '0001_initial'))

    另外在迁移未执行时,请考虑好什么是你想要发生的。你可以什么都不做(就像上面的示例)或者从新应用中移除一些或全部的数据。相应的调整 操作的第二个参数。