writing-migrations.txt 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. ===========================
  2. Writing database migrations
  3. ===========================
  4. This document explains how to structure and write database migrations for
  5. different scenarios you might encounter. For introductory material on
  6. migrations, see :doc:`the topic guide </topics/migrations>`.
  7. .. _data-migrations-and-multiple-databases:
  8. Data migrations and multiple databases
  9. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  10. When using multiple databases, you may need to figure out whether or not to
  11. run a migration against a particular database. For example, you may want to
  12. **only** run a migration on a particular database.
  13. In order to do that you can check the database connection's alias inside a
  14. ``RunPython`` operation by looking at the ``schema_editor.connection.alias``
  15. attribute::
  16. from django.db import migrations
  17. def forwards(apps, schema_editor):
  18. if not schema_editor.connection.alias == 'default':
  19. return
  20. # Your migration code goes here
  21. class Migration(migrations.Migration):
  22. dependencies = [
  23. # Dependencies to other migrations
  24. ]
  25. operations = [
  26. migrations.RunPython(forwards),
  27. ]
  28. .. versionadded:: 1.8
  29. You can also provide hints that will be passed to the :meth:`allow_migrate()`
  30. method of database routers as ``**hints``:
  31. .. snippet::
  32. :filename: myapp/dbrouters.py
  33. class MyRouter(object):
  34. def allow_migrate(self, db, app_label, model_name=None, **hints):
  35. if 'target_db' in hints:
  36. return db == hints['target_db']
  37. return True
  38. Then, to leverage this in your migrations, do the following::
  39. from django.db import migrations
  40. def forwards(apps, schema_editor):
  41. # Your migration code goes here
  42. ...
  43. class Migration(migrations.Migration):
  44. dependencies = [
  45. # Dependencies to other migrations
  46. ]
  47. operations = [
  48. migrations.RunPython(forwards, hints={'target_db': 'default'}),
  49. ]
  50. If your ``RunPython`` or ``RunSQL`` operation only affects one model, it's good
  51. practice to pass ``model_name`` as a hint to make it as transparent as possible
  52. to the router. This is especially important for reusable and third-party apps.
  53. Migrations that add unique fields
  54. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  55. Applying a "plain" migration that adds a unique non-nullable field to a table
  56. with existing rows will raise an error because the value used to populate
  57. existing rows is generated only once, thus breaking the unique constraint.
  58. Therefore, the following steps should be taken. In this example, we'll add a
  59. non-nullable :class:`~django.db.models.UUIDField` with a default value. Modify
  60. the respective field according to your needs.
  61. * Add the field on your model with ``default=uuid.uuid4`` and ``unique=True``
  62. arguments (choose an appropriate default for the type of the field you're
  63. adding).
  64. * Run the :djadmin:`makemigrations` command. This should generate a migration
  65. with an ``AddField`` operation.
  66. * Generate two empty migration files for the same app by running
  67. ``makemigrations myapp --empty`` twice. We've renamed the migration files to
  68. give them meaningful names in the examples below.
  69. * Copy the ``AddField`` operation from the auto-generated migration (the first
  70. of the three new files) to the last migration and change ``AddField`` to
  71. ``AlterField``. For example:
  72. .. snippet::
  73. :filename: 0006_remove_uuid_null.py
  74. # -*- coding: utf-8 -*-
  75. from __future__ import unicode_literals
  76. from django.db import migrations, models
  77. import uuid
  78. class Migration(migrations.Migration):
  79. dependencies = [
  80. ('myapp', '0005_populate_uuid_values'),
  81. ]
  82. operations = [
  83. migrations.AlterField(
  84. model_name='mymodel',
  85. name='uuid',
  86. field=models.UUIDField(default=uuid.uuid4, unique=True),
  87. ),
  88. ]
  89. * Edit the first migration file. The generated migration class should look
  90. similar to this:
  91. .. snippet::
  92. :filename: 0004_add_uuid_field.py
  93. class Migration(migrations.Migration):
  94. dependencies = [
  95. ('myapp', '0003_auto_20150129_1705'),
  96. ]
  97. operations = [
  98. migrations.AddField(
  99. model_name='mymodel',
  100. name='uuid',
  101. field=models.UUIDField(default=uuid.uuid4, unique=True),
  102. ),
  103. ]
  104. Change ``unique=True`` to ``null=True`` -- this will create the intermediary
  105. null field and defer creating the unique constraint until we've populated
  106. unique values on all the rows.
  107. * In the first empty migration file, add a
  108. :class:`~django.db.migrations.operations.RunPython` or
  109. :class:`~django.db.migrations.operations.RunSQL` operation to generate a
  110. unique value (UUID in the example) for each existing row. For example:
  111. .. snippet::
  112. :filename: 0005_populate_uuid_values.py
  113. # -*- coding: utf-8 -*-
  114. from __future__ import unicode_literals
  115. from django.db import migrations, models
  116. import uuid
  117. def gen_uuid(apps, schema_editor):
  118. MyModel = apps.get_model('myapp', 'MyModel')
  119. for row in MyModel.objects.all():
  120. row.uuid = uuid.uuid4()
  121. row.save()
  122. class Migration(migrations.Migration):
  123. dependencies = [
  124. ('myapp', '0004_add_uuid_field'),
  125. ]
  126. operations = [
  127. # omit reverse_code=... if you don't want the migration to be reversible.
  128. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
  129. ]
  130. * Now you can apply the migrations as usual with the :djadmin:`migrate` command.
  131. Note there is a race condition if you allow objects to be created while this
  132. migration is running. Objects created after the ``AddField`` and before
  133. ``RunPython`` will have their original ``uuid``’s overwritten.
  134. Controlling the order of migrations
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. Django determines the order in which migrations should be applied not by the
  137. filename of each migration, but by building a graph using two properties on the
  138. ``Migration`` class: ``dependencies`` and ``run_before``.
  139. If you've used the :djadmin:`makemigrations` command you've probably
  140. already seen ``dependencies`` in action because auto-created
  141. migrations have this defined as part of their creation process.
  142. The ``dependencies`` property is declared like this::
  143. from django.db import migrations
  144. class Migration(migrations.Migration):
  145. dependencies = [
  146. ('myapp', '0123_the_previous_migration'),
  147. ]
  148. Usually this will be enough, but from time to time you may need to
  149. ensure that your migration runs *before* other migrations. This is
  150. useful, for example, to make third-party apps' migrations run *after*
  151. your :setting:`AUTH_USER_MODEL` replacement.
  152. To achieve this, place all migrations that should depend on yours in
  153. the ``run_before`` attribute on your ``Migration`` class::
  154. class Migration(migrations.Migration):
  155. ...
  156. run_before = [
  157. ('third_party_app', '0001_do_awesome'),
  158. ]
  159. Prefer using ``dependencies`` over ``run_before`` when possible. You should
  160. only use ``run_before`` if it is undesirable or impractical to specify
  161. ``dependencies`` in the migration which you want to run after the one you are
  162. writing.