1. =================================
    
  2. How to create database migrations
    
  3. =================================
    
  4. 
    
  5. This document explains how to structure and write database migrations for
    
  6. different scenarios you might encounter. For introductory material on
    
  7. migrations, see :doc:`the topic guide </topics/migrations>`.
    
  8. 
    
  9. .. _data-migrations-and-multiple-databases:
    
  10. 
    
  11. Data migrations and multiple databases
    
  12. ======================================
    
  13. 
    
  14. When using multiple databases, you may need to figure out whether or not to
    
  15. run a migration against a particular database. For example, you may want to
    
  16. **only** run a migration on a particular database.
    
  17. 
    
  18. In order to do that you can check the database connection's alias inside a
    
  19. ``RunPython`` operation by looking at the ``schema_editor.connection.alias``
    
  20. attribute::
    
  21. 
    
  22.     from django.db import migrations
    
  23. 
    
  24.     def forwards(apps, schema_editor):
    
  25.         if schema_editor.connection.alias != 'default':
    
  26.             return
    
  27.         # Your migration code goes here
    
  28. 
    
  29.     class Migration(migrations.Migration):
    
  30. 
    
  31.         dependencies = [
    
  32.             # Dependencies to other migrations
    
  33.         ]
    
  34. 
    
  35.         operations = [
    
  36.             migrations.RunPython(forwards),
    
  37.         ]
    
  38. 
    
  39. You can also provide hints that will be passed to the :meth:`allow_migrate()`
    
  40. method of database routers as ``**hints``:
    
  41. 
    
  42. .. code-block:: python
    
  43.     :caption: ``myapp/dbrouters.py``
    
  44. 
    
  45.     class MyRouter:
    
  46. 
    
  47.         def allow_migrate(self, db, app_label, model_name=None, **hints):
    
  48.             if 'target_db' in hints:
    
  49.                 return db == hints['target_db']
    
  50.             return True
    
  51. 
    
  52. Then, to leverage this in your migrations, do the following::
    
  53. 
    
  54.     from django.db import migrations
    
  55. 
    
  56.     def forwards(apps, schema_editor):
    
  57.         # Your migration code goes here
    
  58.         ...
    
  59. 
    
  60.     class Migration(migrations.Migration):
    
  61. 
    
  62.         dependencies = [
    
  63.             # Dependencies to other migrations
    
  64.         ]
    
  65. 
    
  66.         operations = [
    
  67.             migrations.RunPython(forwards, hints={'target_db': 'default'}),
    
  68.         ]
    
  69. 
    
  70. If your ``RunPython`` or ``RunSQL`` operation only affects one model, it's good
    
  71. practice to pass ``model_name`` as a hint to make it as transparent as possible
    
  72. to the router. This is especially important for reusable and third-party apps.
    
  73. 
    
  74. Migrations that add unique fields
    
  75. =================================
    
  76. 
    
  77. Applying a "plain" migration that adds a unique non-nullable field to a table
    
  78. with existing rows will raise an error because the value used to populate
    
  79. existing rows is generated only once, thus breaking the unique constraint.
    
  80. 
    
  81. Therefore, the following steps should be taken. In this example, we'll add a
    
  82. non-nullable :class:`~django.db.models.UUIDField` with a default value. Modify
    
  83. the respective field according to your needs.
    
  84. 
    
  85. * Add the field on your model with ``default=uuid.uuid4`` and ``unique=True``
    
  86.   arguments (choose an appropriate default for the type of the field you're
    
  87.   adding).
    
  88. 
    
  89. * Run the :djadmin:`makemigrations` command. This should generate a migration
    
  90.   with an ``AddField`` operation.
    
  91. 
    
  92. * Generate two empty migration files for the same app by running
    
  93.   ``makemigrations myapp --empty`` twice. We've renamed the migration files to
    
  94.   give them meaningful names in the examples below.
    
  95. 
    
  96. * Copy the ``AddField`` operation from the auto-generated migration (the first
    
  97.   of the three new files) to the last migration, change ``AddField`` to
    
  98.   ``AlterField``, and add imports of ``uuid`` and ``models``. For example:
    
  99. 
    
  100.   .. code-block:: python
    
  101.     :caption: ``0006_remove_uuid_null.py``
    
  102. 
    
  103.     # Generated by Django A.B on YYYY-MM-DD HH:MM
    
  104.     from django.db import migrations, models
    
  105.     import uuid
    
  106. 
    
  107.     class Migration(migrations.Migration):
    
  108. 
    
  109.         dependencies = [
    
  110.             ('myapp', '0005_populate_uuid_values'),
    
  111.         ]
    
  112. 
    
  113.         operations = [
    
  114.             migrations.AlterField(
    
  115.                 model_name='mymodel',
    
  116.                 name='uuid',
    
  117.                 field=models.UUIDField(default=uuid.uuid4, unique=True),
    
  118.             ),
    
  119.         ]
    
  120. 
    
  121. * Edit the first migration file. The generated migration class should look
    
  122.   similar to this:
    
  123. 
    
  124.   .. code-block:: python
    
  125.     :caption: ``0004_add_uuid_field.py``
    
  126. 
    
  127.     class Migration(migrations.Migration):
    
  128. 
    
  129.         dependencies = [
    
  130.             ('myapp', '0003_auto_20150129_1705'),
    
  131.         ]
    
  132. 
    
  133.         operations = [
    
  134.             migrations.AddField(
    
  135.                 model_name='mymodel',
    
  136.                 name='uuid',
    
  137.                 field=models.UUIDField(default=uuid.uuid4, unique=True),
    
  138.             ),
    
  139.         ]
    
  140. 
    
  141.   Change ``unique=True`` to ``null=True`` -- this will create the intermediary
    
  142.   null field and defer creating the unique constraint until we've populated
    
  143.   unique values on all the rows.
    
  144. 
    
  145. * In the first empty migration file, add a
    
  146.   :class:`~django.db.migrations.operations.RunPython` or
    
  147.   :class:`~django.db.migrations.operations.RunSQL` operation to generate a
    
  148.   unique value (UUID in the example) for each existing row. Also add an import
    
  149.   of ``uuid``. For example:
    
  150. 
    
  151.   .. code-block:: python
    
  152.     :caption: ``0005_populate_uuid_values.py``
    
  153. 
    
  154.     # Generated by Django A.B on YYYY-MM-DD HH:MM
    
  155.     from django.db import migrations
    
  156.     import uuid
    
  157. 
    
  158.     def gen_uuid(apps, schema_editor):
    
  159.         MyModel = apps.get_model('myapp', 'MyModel')
    
  160.         for row in MyModel.objects.all():
    
  161.             row.uuid = uuid.uuid4()
    
  162.             row.save(update_fields=['uuid'])
    
  163. 
    
  164.     class Migration(migrations.Migration):
    
  165. 
    
  166.         dependencies = [
    
  167.             ('myapp', '0004_add_uuid_field'),
    
  168.         ]
    
  169. 
    
  170.         operations = [
    
  171.             # omit reverse_code=... if you don't want the migration to be reversible.
    
  172.             migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
    
  173.         ]
    
  174. 
    
  175. * Now you can apply the migrations as usual with the :djadmin:`migrate` command.
    
  176. 
    
  177.   Note there is a race condition if you allow objects to be created while this
    
  178.   migration is running. Objects created after the ``AddField`` and before
    
  179.   ``RunPython`` will have their original ``uuid``’s overwritten.
    
  180. 
    
  181. .. _non-atomic-migrations:
    
  182. 
    
  183. Non-atomic migrations
    
  184. ~~~~~~~~~~~~~~~~~~~~~
    
  185. 
    
  186. On databases that support DDL transactions (SQLite and PostgreSQL), migrations
    
  187. will run inside a transaction by default. For use cases such as performing data
    
  188. migrations on large tables, you may want to prevent a migration from running in
    
  189. a transaction by setting the ``atomic`` attribute to ``False``::
    
  190. 
    
  191.     from django.db import migrations
    
  192. 
    
  193.     class Migration(migrations.Migration):
    
  194.         atomic = False
    
  195. 
    
  196. Within such a migration, all operations are run without a transaction. It's
    
  197. possible to execute parts of the migration inside a transaction using
    
  198. :func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to
    
  199. ``RunPython``.
    
  200. 
    
  201. Here's an example of a non-atomic data migration that updates a large table in
    
  202. smaller batches::
    
  203. 
    
  204.     import uuid
    
  205. 
    
  206.     from django.db import migrations, transaction
    
  207. 
    
  208.     def gen_uuid(apps, schema_editor):
    
  209.         MyModel = apps.get_model('myapp', 'MyModel')
    
  210.         while MyModel.objects.filter(uuid__isnull=True).exists():
    
  211.             with transaction.atomic():
    
  212.                 for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:
    
  213.                     row.uuid = uuid.uuid4()
    
  214.                     row.save()
    
  215. 
    
  216.     class Migration(migrations.Migration):
    
  217.         atomic = False
    
  218. 
    
  219.         operations = [
    
  220.             migrations.RunPython(gen_uuid),
    
  221.         ]
    
  222. 
    
  223. The ``atomic`` attribute doesn't have an effect on databases that don't support
    
  224. DDL transactions (e.g. MySQL, Oracle). (MySQL's `atomic DDL statement support
    
  225. <https://dev.mysql.com/doc/refman/en/atomic-ddl.html>`_ refers to individual
    
  226. statements rather than multiple statements wrapped in a transaction that can be
    
  227. rolled back.)
    
  228. 
    
  229. Controlling the order of migrations
    
  230. ===================================
    
  231. 
    
  232. Django determines the order in which migrations should be applied not by the
    
  233. filename of each migration, but by building a graph using two properties on the
    
  234. ``Migration`` class: ``dependencies`` and ``run_before``.
    
  235. 
    
  236. If you've used the :djadmin:`makemigrations` command you've probably
    
  237. already seen ``dependencies`` in action because auto-created
    
  238. migrations have this defined as part of their creation process.
    
  239. 
    
  240. The ``dependencies`` property is declared like this::
    
  241. 
    
  242.     from django.db import migrations
    
  243. 
    
  244.     class Migration(migrations.Migration):
    
  245. 
    
  246.         dependencies = [
    
  247.             ('myapp', '0123_the_previous_migration'),
    
  248.         ]
    
  249. 
    
  250. Usually this will be enough, but from time to time you may need to
    
  251. ensure that your migration runs *before* other migrations. This is
    
  252. useful, for example, to make third-party apps' migrations run *after*
    
  253. your :setting:`AUTH_USER_MODEL` replacement.
    
  254. 
    
  255. To achieve this, place all migrations that should depend on yours in
    
  256. the ``run_before`` attribute on your ``Migration`` class::
    
  257. 
    
  258.     class Migration(migrations.Migration):
    
  259.         ...
    
  260. 
    
  261.         run_before = [
    
  262.             ('third_party_app', '0001_do_awesome'),
    
  263.         ]
    
  264. 
    
  265. Prefer using ``dependencies`` over ``run_before`` when possible. You should
    
  266. only use ``run_before`` if it is undesirable or impractical to specify
    
  267. ``dependencies`` in the migration which you want to run after the one you are
    
  268. writing.
    
  269. 
    
  270. Migrating data between third-party apps
    
  271. =======================================
    
  272. 
    
  273. You can use a data migration to move data from one third-party application to
    
  274. another.
    
  275. 
    
  276. If you plan to remove the old app later, you'll need to set the ``dependencies``
    
  277. property based on whether or not the old app is installed. Otherwise, you'll
    
  278. have missing dependencies once you uninstall the old app. Similarly, you'll
    
  279. need to catch :exc:`LookupError` in the ``apps.get_model()`` call that
    
  280. retrieves models from the old app. This approach allows you to deploy your
    
  281. project anywhere without first installing and then uninstalling the old app.
    
  282. 
    
  283. Here's a sample migration:
    
  284. 
    
  285. .. code-block:: python
    
  286.     :caption: ``myapp/migrations/0124_move_old_app_to_new_app.py``
    
  287. 
    
  288.     from django.apps import apps as global_apps
    
  289.     from django.db import migrations
    
  290. 
    
  291.     def forwards(apps, schema_editor):
    
  292.         try:
    
  293.             OldModel = apps.get_model('old_app', 'OldModel')
    
  294.         except LookupError:
    
  295.             # The old app isn't installed.
    
  296.             return
    
  297. 
    
  298.         NewModel = apps.get_model('new_app', 'NewModel')
    
  299.         NewModel.objects.bulk_create(
    
  300.             NewModel(new_attribute=old_object.old_attribute)
    
  301.             for old_object in OldModel.objects.all()
    
  302.         )
    
  303. 
    
  304.     class Migration(migrations.Migration):
    
  305.         operations = [
    
  306.             migrations.RunPython(forwards, migrations.RunPython.noop),
    
  307.         ]
    
  308.         dependencies = [
    
  309.             ('myapp', '0123_the_previous_migration'),
    
  310.             ('new_app', '0001_initial'),
    
  311.         ]
    
  312. 
    
  313.         if global_apps.is_installed('old_app'):
    
  314.             dependencies.append(('old_app', '0001_initial'))
    
  315. 
    
  316. Also consider what you want to happen when the migration is unapplied. You
    
  317. could either do nothing (as in the example above) or remove some or all of the
    
  318. data from the new application. Adjust the second argument of the
    
  319. :mod:`~django.db.migrations.operations.RunPython` operation accordingly.
    
  320. 
    
  321. .. _changing-a-manytomanyfield-to-use-a-through-model:
    
  322. 
    
  323. Changing a ``ManyToManyField`` to use a ``through`` model
    
  324. =========================================================
    
  325. 
    
  326. If you change a :class:`~django.db.models.ManyToManyField` to use a ``through``
    
  327. model, the default migration will delete the existing table and create a new
    
  328. one, losing the existing relations. To avoid this, you can use
    
  329. :class:`.SeparateDatabaseAndState` to rename the existing table to the new
    
  330. table name while telling the migration autodetector that the new model has
    
  331. been created. You can check the existing table name through
    
  332. :djadmin:`sqlmigrate` or :djadmin:`dbshell`. You can check the new table name
    
  333. with the through model's ``_meta.db_table`` property. Your new ``through``
    
  334. model should use the same names for the ``ForeignKey``\s as Django did. Also if
    
  335. it needs any extra fields, they should be added in operations after
    
  336. :class:`.SeparateDatabaseAndState`.
    
  337. 
    
  338. For example, if we had a ``Book`` model with a ``ManyToManyField`` linking to
    
  339. ``Author``, we could add a through model ``AuthorBook`` with a new field
    
  340. ``is_primary``, like so::
    
  341. 
    
  342.     from django.db import migrations, models
    
  343.     import django.db.models.deletion
    
  344. 
    
  345. 
    
  346.     class Migration(migrations.Migration):
    
  347.         dependencies = [
    
  348.             ('core', '0001_initial'),
    
  349.         ]
    
  350. 
    
  351.         operations = [
    
  352.             migrations.SeparateDatabaseAndState(
    
  353.                 database_operations=[
    
  354.                     # Old table name from checking with sqlmigrate, new table
    
  355.                     # name from AuthorBook._meta.db_table.
    
  356.                     migrations.RunSQL(
    
  357.                         sql='ALTER TABLE core_book_authors RENAME TO core_authorbook',
    
  358.                         reverse_sql='ALTER TABLE core_authorbook RENAME TO core_book_authors',
    
  359.                     ),
    
  360.                 ],
    
  361.                 state_operations=[
    
  362.                     migrations.CreateModel(
    
  363.                         name='AuthorBook',
    
  364.                         fields=[
    
  365.                             (
    
  366.                                 'id',
    
  367.                                 models.AutoField(
    
  368.                                     auto_created=True,
    
  369.                                     primary_key=True,
    
  370.                                     serialize=False,
    
  371.                                     verbose_name='ID',
    
  372.                                 ),
    
  373.                             ),
    
  374.                             (
    
  375.                                 'author',
    
  376.                                 models.ForeignKey(
    
  377.                                     on_delete=django.db.models.deletion.DO_NOTHING,
    
  378.                                     to='core.Author',
    
  379.                                 ),
    
  380.                             ),
    
  381.                             (
    
  382.                                 'book',
    
  383.                                 models.ForeignKey(
    
  384.                                     on_delete=django.db.models.deletion.DO_NOTHING,
    
  385.                                     to='core.Book',
    
  386.                                 ),
    
  387.                             ),
    
  388.                         ],
    
  389.                     ),
    
  390.                     migrations.AlterField(
    
  391.                         model_name='book',
    
  392.                         name='authors',
    
  393.                         field=models.ManyToManyField(
    
  394.                             to='core.Author',
    
  395.                             through='core.AuthorBook',
    
  396.                         ),
    
  397.                     ),
    
  398.                 ],
    
  399.             ),
    
  400.             migrations.AddField(
    
  401.                 model_name='authorbook',
    
  402.                 name='is_primary',
    
  403.                 field=models.BooleanField(default=False),
    
  404.             ),
    
  405.         ]
    
  406. 
    
  407. Changing an unmanaged model to managed
    
  408. ======================================
    
  409. 
    
  410. If you want to change an unmanaged model (:attr:`managed=False
    
  411. <django.db.models.Options.managed>`) to managed, you must remove
    
  412. ``managed=False`` and generate a migration before making other schema-related
    
  413. changes to the model, since schema changes that appear in the migration that
    
  414. contains the operation to change ``Meta.managed`` may not be applied.