2
0

writing-migrations.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. =================================
  2. How to create 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 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. .. code-block:: python
  31. :caption: ``myapp/dbrouters.py``
  32. class MyRouter:
  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, change ``AddField`` to
  70. ``AlterField``, and add imports of ``uuid`` and ``models``. For example:
  71. .. code-block:: python
  72. :caption: ``0006_remove_uuid_null.py``
  73. # Generated by Django A.B on YYYY-MM-DD HH:MM
  74. from django.db import migrations, models
  75. import uuid
  76. class Migration(migrations.Migration):
  77. dependencies = [
  78. ("myapp", "0005_populate_uuid_values"),
  79. ]
  80. operations = [
  81. migrations.AlterField(
  82. model_name="mymodel",
  83. name="uuid",
  84. field=models.UUIDField(default=uuid.uuid4, unique=True),
  85. ),
  86. ]
  87. * Edit the first migration file. The generated migration class should look
  88. similar to this:
  89. .. code-block:: python
  90. :caption: ``0004_add_uuid_field.py``
  91. class Migration(migrations.Migration):
  92. dependencies = [
  93. ("myapp", "0003_auto_20150129_1705"),
  94. ]
  95. operations = [
  96. migrations.AddField(
  97. model_name="mymodel",
  98. name="uuid",
  99. field=models.UUIDField(default=uuid.uuid4, unique=True),
  100. ),
  101. ]
  102. Change ``unique=True`` to ``null=True`` -- this will create the intermediary
  103. null field and defer creating the unique constraint until we've populated
  104. unique values on all the rows.
  105. * In the first empty migration file, add a
  106. :class:`~django.db.migrations.operations.RunPython` or
  107. :class:`~django.db.migrations.operations.RunSQL` operation to generate a
  108. unique value (UUID in the example) for each existing row. Also add an import
  109. of ``uuid``. For example:
  110. .. code-block:: python
  111. :caption: ``0005_populate_uuid_values.py``
  112. # Generated by Django A.B on YYYY-MM-DD HH:MM
  113. from django.db import migrations
  114. import uuid
  115. def gen_uuid(apps, schema_editor):
  116. MyModel = apps.get_model("myapp", "MyModel")
  117. for row in MyModel.objects.all():
  118. row.uuid = uuid.uuid4()
  119. row.save(update_fields=["uuid"])
  120. class Migration(migrations.Migration):
  121. dependencies = [
  122. ("myapp", "0004_add_uuid_field"),
  123. ]
  124. operations = [
  125. # omit reverse_code=... if you don't want the migration to be reversible.
  126. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
  127. ]
  128. * Now you can apply the migrations as usual with the :djadmin:`migrate` command.
  129. Note there is a race condition if you allow objects to be created while this
  130. migration is running. Objects created after the ``AddField`` and before
  131. ``RunPython`` will have their original ``uuid``’s overwritten.
  132. .. _non-atomic-migrations:
  133. Non-atomic migrations
  134. ~~~~~~~~~~~~~~~~~~~~~
  135. On databases that support DDL transactions (SQLite and PostgreSQL), migrations
  136. will run inside a transaction by default. For use cases such as performing data
  137. migrations on large tables, you may want to prevent a migration from running in
  138. a transaction by setting the ``atomic`` attribute to ``False``::
  139. from django.db import migrations
  140. class Migration(migrations.Migration):
  141. atomic = False
  142. Within such a migration, all operations are run without a transaction. It's
  143. possible to execute parts of the migration inside a transaction using
  144. :func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to
  145. ``RunPython``.
  146. Here's an example of a non-atomic data migration that updates a large table in
  147. smaller batches::
  148. import uuid
  149. from django.db import migrations, transaction
  150. def gen_uuid(apps, schema_editor):
  151. MyModel = apps.get_model("myapp", "MyModel")
  152. while MyModel.objects.filter(uuid__isnull=True).exists():
  153. with transaction.atomic():
  154. for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:
  155. row.uuid = uuid.uuid4()
  156. row.save()
  157. class Migration(migrations.Migration):
  158. atomic = False
  159. operations = [
  160. migrations.RunPython(gen_uuid),
  161. ]
  162. The ``atomic`` attribute doesn't have an effect on databases that don't support
  163. DDL transactions (e.g. MySQL, Oracle). (MySQL's `atomic DDL statement support
  164. <https://dev.mysql.com/doc/refman/en/atomic-ddl.html>`_ refers to individual
  165. statements rather than multiple statements wrapped in a transaction that can be
  166. rolled back.)
  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. .. code-block:: python
  208. :caption: ``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-a-manytomanyfield-to-use-a-through-model:
  237. Changing a ``ManyToManyField`` to use a ``through`` model
  238. =========================================================
  239. If you change a :class:`~django.db.models.ManyToManyField` to use a ``through``
  240. model, the default migration will delete the existing table and create a new
  241. one, losing the existing relations. To avoid this, you can use
  242. :class:`.SeparateDatabaseAndState` to rename the existing table to the new
  243. table name while telling the migration autodetector that the new model has
  244. been created. You can check the existing table name through
  245. :djadmin:`sqlmigrate` or :djadmin:`dbshell`. You can check the new table name
  246. with the through model's ``_meta.db_table`` property. Your new ``through``
  247. model should use the same names for the ``ForeignKey``\s as Django did. Also if
  248. it needs any extra fields, they should be added in operations after
  249. :class:`.SeparateDatabaseAndState`.
  250. For example, if we had a ``Book`` model with a ``ManyToManyField`` linking to
  251. ``Author``, we could add a through model ``AuthorBook`` with a new field
  252. ``is_primary``, like so::
  253. from django.db import migrations, models
  254. import django.db.models.deletion
  255. class Migration(migrations.Migration):
  256. dependencies = [
  257. ("core", "0001_initial"),
  258. ]
  259. operations = [
  260. migrations.SeparateDatabaseAndState(
  261. database_operations=[
  262. # Old table name from checking with sqlmigrate, new table
  263. # name from AuthorBook._meta.db_table.
  264. migrations.RunSQL(
  265. sql="ALTER TABLE core_book_authors RENAME TO core_authorbook",
  266. reverse_sql="ALTER TABLE core_authorbook RENAME TO core_book_authors",
  267. ),
  268. ],
  269. state_operations=[
  270. migrations.CreateModel(
  271. name="AuthorBook",
  272. fields=[
  273. (
  274. "id",
  275. models.AutoField(
  276. auto_created=True,
  277. primary_key=True,
  278. serialize=False,
  279. verbose_name="ID",
  280. ),
  281. ),
  282. (
  283. "author",
  284. models.ForeignKey(
  285. on_delete=django.db.models.deletion.DO_NOTHING,
  286. to="core.Author",
  287. ),
  288. ),
  289. (
  290. "book",
  291. models.ForeignKey(
  292. on_delete=django.db.models.deletion.DO_NOTHING,
  293. to="core.Book",
  294. ),
  295. ),
  296. ],
  297. ),
  298. migrations.AlterField(
  299. model_name="book",
  300. name="authors",
  301. field=models.ManyToManyField(
  302. to="core.Author",
  303. through="core.AuthorBook",
  304. ),
  305. ),
  306. ],
  307. ),
  308. migrations.AddField(
  309. model_name="authorbook",
  310. name="is_primary",
  311. field=models.BooleanField(default=False),
  312. ),
  313. ]
  314. Changing an unmanaged model to managed
  315. ======================================
  316. If you want to change an unmanaged model (:attr:`managed=False
  317. <django.db.models.Options.managed>`) to managed, you must remove
  318. ``managed=False`` and generate a migration before making other schema-related
  319. changes to the model, since schema changes that appear in the migration that
  320. contains the operation to change ``Meta.managed`` may not be applied.