writing-migrations.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. On databases that support DDL transactions (SQLite and PostgreSQL), migrations
  139. will run inside a transaction by default. For use cases such as performing data
  140. migrations on large tables, you may want to prevent a migration from running in
  141. a transaction by setting the ``atomic`` attribute to ``False``::
  142. from django.db import migrations
  143. class Migration(migrations.Migration):
  144. atomic = False
  145. Within such a migration, all operations are run without a transaction. It's
  146. possible to execute parts of the migration inside a transaction using
  147. :func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to
  148. ``RunPython``.
  149. Here's an example of a non-atomic data migration that updates a large table in
  150. smaller batches::
  151. import uuid
  152. from django.db import migrations, transaction
  153. def gen_uuid(apps, schema_editor):
  154. MyModel = apps.get_model('myapp', 'MyModel')
  155. while MyModel.objects.filter(uuid__isnull=True).exists():
  156. with transaction.atomic():
  157. for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:
  158. row.uuid = uuid.uuid4()
  159. row.save()
  160. class Migration(migrations.Migration):
  161. atomic = False
  162. operations = [
  163. migrations.RunPython(gen_uuid),
  164. ]
  165. The ``atomic`` attribute doesn't have an effect on databases that don't support
  166. DDL transactions (e.g. MySQL, Oracle).
  167. Controlling the order of migrations
  168. ===================================
  169. Django determines the order in which migrations should be applied not by the
  170. filename of each migration, but by building a graph using two properties on the
  171. ``Migration`` class: ``dependencies`` and ``run_before``.
  172. If you've used the :djadmin:`makemigrations` command you've probably
  173. already seen ``dependencies`` in action because auto-created
  174. migrations have this defined as part of their creation process.
  175. The ``dependencies`` property is declared like this::
  176. from django.db import migrations
  177. class Migration(migrations.Migration):
  178. dependencies = [
  179. ('myapp', '0123_the_previous_migration'),
  180. ]
  181. Usually this will be enough, but from time to time you may need to
  182. ensure that your migration runs *before* other migrations. This is
  183. useful, for example, to make third-party apps' migrations run *after*
  184. your :setting:`AUTH_USER_MODEL` replacement.
  185. To achieve this, place all migrations that should depend on yours in
  186. the ``run_before`` attribute on your ``Migration`` class::
  187. class Migration(migrations.Migration):
  188. ...
  189. run_before = [
  190. ('third_party_app', '0001_do_awesome'),
  191. ]
  192. Prefer using ``dependencies`` over ``run_before`` when possible. You should
  193. only use ``run_before`` if it is undesirable or impractical to specify
  194. ``dependencies`` in the migration which you want to run after the one you are
  195. writing.
  196. Migrating data between third-party apps
  197. =======================================
  198. You can use a data migration to move data from one third-party application to
  199. another.
  200. If you plan to remove the old app later, you'll need to set the ``dependencies``
  201. property based on whether or not the old app is installed. Otherwise, you'll
  202. have missing dependencies once you uninstall the old app. Similarly, you'll
  203. need to catch :exc:`LookupError` in the ``apps.get_model()`` call that
  204. retrieves models from the old app. This approach allows you to deploy your
  205. project anywhere without first installing and then uninstalling the old app.
  206. Here's a sample migration:
  207. .. snippet::
  208. :filename: myapp/migrations/0124_move_old_app_to_new_app.py
  209. from django.apps import apps as global_apps
  210. from django.db import migrations
  211. def forwards(apps, schema_editor):
  212. try:
  213. OldModel = apps.get_model('old_app', 'OldModel')
  214. except LookupError:
  215. # The old app isn't installed.
  216. return
  217. NewModel = apps.get_model('new_app', 'NewModel')
  218. NewModel.objects.bulk_create(
  219. NewModel(new_attribute=old_object.old_attribute)
  220. for old_object in OldModel.objects.all()
  221. )
  222. class Migration(migrations.Migration):
  223. operations = [
  224. migrations.RunPython(forwards, migrations.RunPython.noop),
  225. ]
  226. dependencies = [
  227. ('myapp', '0123_the_previous_migration'),
  228. ('new_app', '0001_initial'),
  229. ]
  230. if global_apps.is_installed('old_app'):
  231. dependencies.append(('old_app', '0001_initial'))
  232. Also consider what you want to happen when the migration is unapplied. You
  233. could either do nothing (as in the example above) or remove some or all of the
  234. data from the new application. Adjust the second argument of the
  235. :mod:`~django.db.migrations.operations.RunPython` operation accordingly.
  236. Changing an unmanaged model to managed
  237. ======================================
  238. If you want to change an unmanaged model (:attr:`managed=False
  239. <django.db.models.Options.managed>`) to managed, you must remove
  240. ``managed=False`` and generate a migration before making other schema-related
  241. changes to the model, since schema changes that appear in the migration that
  242. contains the operation to change ``Meta.managed`` may not be applied.