writing-migrations.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. You can also provide hints that will be passed to the :meth:`allow_migrate()`
  29. method of database routers as ``**hints``:
  30. .. snippet::
  31. :filename: myapp/dbrouters.py
  32. class MyRouter(object):
  33. def allow_migrate(self, db, app_label, model_name=None, **hints):
  34. if 'target_db' in hints:
  35. return db == hints['target_db']
  36. return True
  37. Then, to leverage this in your migrations, do the following::
  38. from django.db import migrations
  39. def forwards(apps, schema_editor):
  40. # Your migration code goes here
  41. ...
  42. class Migration(migrations.Migration):
  43. dependencies = [
  44. # Dependencies to other migrations
  45. ]
  46. operations = [
  47. migrations.RunPython(forwards, hints={'target_db': 'default'}),
  48. ]
  49. If your ``RunPython`` or ``RunSQL`` operation only affects one model, it's good
  50. practice to pass ``model_name`` as a hint to make it as transparent as possible
  51. to the router. This is especially important for reusable and third-party apps.
  52. Migrations that add unique fields
  53. =================================
  54. Applying a "plain" migration that adds a unique non-nullable field to a table
  55. with existing rows will raise an error because the value used to populate
  56. existing rows is generated only once, thus breaking the unique constraint.
  57. Therefore, the following steps should be taken. In this example, we'll add a
  58. non-nullable :class:`~django.db.models.UUIDField` with a default value. Modify
  59. the respective field according to your needs.
  60. * Add the field on your model with ``default=uuid.uuid4`` and ``unique=True``
  61. arguments (choose an appropriate default for the type of the field you're
  62. adding).
  63. * Run the :djadmin:`makemigrations` command. This should generate a migration
  64. with an ``AddField`` operation.
  65. * Generate two empty migration files for the same app by running
  66. ``makemigrations myapp --empty`` twice. We've renamed the migration files to
  67. give them meaningful names in the examples below.
  68. * Copy the ``AddField`` operation from the auto-generated migration (the first
  69. of the three new files) to the last migration and change ``AddField`` to
  70. ``AlterField``. For example:
  71. .. snippet::
  72. :filename: 0006_remove_uuid_null.py
  73. # -*- coding: utf-8 -*-
  74. # Generated by Django A.B on YYYY-MM-DD HH:MM
  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. # Generated by Django A.B on YYYY-MM-DD HH:MM
  115. from __future__ import unicode_literals
  116. from django.db import migrations, models
  117. import uuid
  118. def gen_uuid(apps, schema_editor):
  119. MyModel = apps.get_model('myapp', 'MyModel')
  120. for row in MyModel.objects.all():
  121. row.uuid = uuid.uuid4()
  122. row.save()
  123. class Migration(migrations.Migration):
  124. dependencies = [
  125. ('myapp', '0004_add_uuid_field'),
  126. ]
  127. operations = [
  128. # omit reverse_code=... if you don't want the migration to be reversible.
  129. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
  130. ]
  131. * Now you can apply the migrations as usual with the :djadmin:`migrate` command.
  132. Note there is a race condition if you allow objects to be created while this
  133. migration is running. Objects created after the ``AddField`` and before
  134. ``RunPython`` will have their original ``uuid``’s overwritten.
  135. .. _non-atomic-migrations:
  136. Non-atomic migrations
  137. ~~~~~~~~~~~~~~~~~~~~~
  138. .. versionadded:: 1.10
  139. On databases that support DDL transactions (SQLite and PostgreSQL), migrations
  140. will run inside a transaction by default. For use cases such as performing data
  141. migrations on large tables, you may want to prevent a migration from running in
  142. a transaction by setting the ``atomic`` attribute to ``False``::
  143. from django.db import migrations
  144. class Migration(migrations.Migration):
  145. atomic = False
  146. Within such a migration, all operations are run without a transaction. It's
  147. possible to execute parts of the migration inside a transaction using
  148. :func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to
  149. ``RunPython``.
  150. Here's an example of a non-atomic data migration that updates a large table in
  151. smaller batches::
  152. import uuid
  153. from django.db import migrations, transaction
  154. def gen_uuid(apps, schema_editor):
  155. MyModel = apps.get_model('myapp', 'MyModel')
  156. while MyModel.objects.filter(uuid__isnull=True).exists():
  157. with transaction.atomic():
  158. for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:
  159. row.uuid = uuid.uuid4()
  160. row.save()
  161. class Migration(migrations.Migration):
  162. atomic = False
  163. operations = [
  164. migrations.RunPython(gen_uuid),
  165. ]
  166. The ``atomic`` attribute doesn't have an effect on databases that don't support
  167. DDL transactions (e.g. MySQL, Oracle).
  168. Controlling the order of migrations
  169. ===================================
  170. Django determines the order in which migrations should be applied not by the
  171. filename of each migration, but by building a graph using two properties on the
  172. ``Migration`` class: ``dependencies`` and ``run_before``.
  173. If you've used the :djadmin:`makemigrations` command you've probably
  174. already seen ``dependencies`` in action because auto-created
  175. migrations have this defined as part of their creation process.
  176. The ``dependencies`` property is declared like this::
  177. from django.db import migrations
  178. class Migration(migrations.Migration):
  179. dependencies = [
  180. ('myapp', '0123_the_previous_migration'),
  181. ]
  182. Usually this will be enough, but from time to time you may need to
  183. ensure that your migration runs *before* other migrations. This is
  184. useful, for example, to make third-party apps' migrations run *after*
  185. your :setting:`AUTH_USER_MODEL` replacement.
  186. To achieve this, place all migrations that should depend on yours in
  187. the ``run_before`` attribute on your ``Migration`` class::
  188. class Migration(migrations.Migration):
  189. ...
  190. run_before = [
  191. ('third_party_app', '0001_do_awesome'),
  192. ]
  193. Prefer using ``dependencies`` over ``run_before`` when possible. You should
  194. only use ``run_before`` if it is undesirable or impractical to specify
  195. ``dependencies`` in the migration which you want to run after the one you are
  196. writing.