migrations.txt 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. ==========
  2. Migrations
  3. ==========
  4. .. module:: django.db.migrations
  5. :synopsis: Schema migration support for Django models
  6. Migrations are Django's way of propagating changes you make to your models
  7. (adding a field, deleting a model, etc.) into your database schema. They're
  8. designed to be mostly automatic, but you'll need to know when to make
  9. migrations, when to run them, and the common problems you might run into.
  10. The Commands
  11. ============
  12. There are several commands which you will use to interact with migrations
  13. and Django's handling of database schema:
  14. * :djadmin:`migrate`, which is responsible for applying and unapplying
  15. migrations.
  16. * :djadmin:`makemigrations`, which is responsible for creating new migrations
  17. based on the changes you have made to your models.
  18. * :djadmin:`sqlmigrate`, which displays the SQL statements for a migration.
  19. * :djadmin:`showmigrations`, which lists a project's migrations and their
  20. status.
  21. You should think of migrations as a version control system for your database
  22. schema. ``makemigrations`` is responsible for packaging up your model changes
  23. into individual migration files - analogous to commits - and ``migrate`` is
  24. responsible for applying those to your database.
  25. The migration files for each app live in a "migrations" directory inside
  26. of that app, and are designed to be committed to, and distributed as part
  27. of, its codebase. You should be making them once on your development machine
  28. and then running the same migrations on your colleagues' machines, your
  29. staging machines, and eventually your production machines.
  30. .. note::
  31. It is possible to override the name of the package which contains the
  32. migrations on a per-app basis by modifying the :setting:`MIGRATION_MODULES`
  33. setting.
  34. Migrations will run the same way on the same dataset and produce consistent
  35. results, meaning that what you see in development and staging is, under the
  36. same circumstances, exactly what will happen in production.
  37. Django will make migrations for any change to your models or fields - even
  38. options that don't affect the database - as the only way it can reconstruct
  39. a field correctly is to have all the changes in the history, and you might
  40. need those options in some data migrations later on (for example, if you've
  41. set custom validators).
  42. Backend Support
  43. ===============
  44. Migrations are supported on all backends that Django ships with, as well
  45. as any third-party backends if they have programmed in support for schema
  46. alteration (done via the :doc:`SchemaEditor </ref/schema-editor>` class).
  47. However, some databases are more capable than others when it comes to
  48. schema migrations; some of the caveats are covered below.
  49. PostgreSQL
  50. ----------
  51. PostgreSQL is the most capable of all the databases here in terms of schema
  52. support.
  53. MySQL
  54. -----
  55. MySQL lacks support for transactions around schema alteration operations,
  56. meaning that if a migration fails to apply you will have to manually unpick
  57. the changes in order to try again (it's impossible to roll back to an
  58. earlier point).
  59. MySQL 8.0 introduced significant performance enhancements for
  60. `DDL operations`_, making them more efficient and reducing the need for full
  61. table rebuilds. However, it cannot guarantee a complete absence of locks or
  62. interruptions. In situations where locks are still necessary, the duration of
  63. these operations will be proportionate to the number of rows involved.
  64. Finally, MySQL has a relatively small limit on the combined size of all columns
  65. an index covers. This means that indexes that are possible on other backends
  66. will fail to be created under MySQL.
  67. .. _DDL operations: https://dev.mysql.com/doc/refman/en/innodb-online-ddl-operations.html
  68. SQLite
  69. ------
  70. SQLite has very little built-in schema alteration support, and so Django
  71. attempts to emulate it by:
  72. * Creating a new table with the new schema
  73. * Copying the data across
  74. * Dropping the old table
  75. * Renaming the new table to match the original name
  76. This process generally works well, but it can be slow and occasionally
  77. buggy. It is not recommended that you run and migrate SQLite in a
  78. production environment unless you are very aware of the risks and
  79. its limitations; the support Django ships with is designed to allow
  80. developers to use SQLite on their local machines to develop less complex
  81. Django projects without the need for a full database.
  82. Workflow
  83. ========
  84. Django can create migrations for you. Make changes to your models - say, add a
  85. field and remove a model - and then run :djadmin:`makemigrations`:
  86. .. code-block:: shell
  87. $ python manage.py makemigrations
  88. Migrations for 'books':
  89. books/migrations/0003_auto.py:
  90. ~ Alter field author on book
  91. Your models will be scanned and compared to the versions currently
  92. contained in your migration files, and then a new set of migrations
  93. will be written out. Make sure to read the output to see what
  94. ``makemigrations`` thinks you have changed - it's not perfect, and for
  95. complex changes it might not be detecting what you expect.
  96. Once you have your new migration files, you should apply them to your
  97. database to make sure they work as expected:
  98. .. code-block:: shell
  99. $ python manage.py migrate
  100. Operations to perform:
  101. Apply all migrations: books
  102. Running migrations:
  103. Rendering model states... DONE
  104. Applying books.0003_auto... OK
  105. Once the migration is applied, commit the migration and the models change
  106. to your version control system as a single commit - that way, when other
  107. developers (or your production servers) check out the code, they'll
  108. get both the changes to your models and the accompanying migration at the
  109. same time.
  110. If you want to give the migration(s) a meaningful name instead of a generated
  111. one, you can use the :option:`makemigrations --name` option:
  112. .. code-block:: shell
  113. $ python manage.py makemigrations --name changed_my_model your_app_label
  114. Version control
  115. ---------------
  116. Because migrations are stored in version control, you'll occasionally
  117. come across situations where you and another developer have both committed
  118. a migration to the same app at the same time, resulting in two migrations
  119. with the same number.
  120. Don't worry - the numbers are just there for developers' reference, Django
  121. just cares that each migration has a different name. Migrations specify which
  122. other migrations they depend on - including earlier migrations in the same
  123. app - in the file, so it's possible to detect when there's two new migrations
  124. for the same app that aren't ordered.
  125. When this happens, Django will prompt you and give you some options. If it
  126. thinks it's safe enough, it will offer to automatically linearize the two
  127. migrations for you. If not, you'll have to go in and modify the migrations
  128. yourself - don't worry, this isn't difficult, and is explained more in
  129. :ref:`migration-files` below.
  130. Transactions
  131. ============
  132. On databases that support DDL transactions (SQLite and PostgreSQL), all
  133. migration operations will run inside a single transaction by default. In
  134. contrast, if a database doesn't support DDL transactions (e.g. MySQL, Oracle)
  135. then all operations will run without a transaction.
  136. You can prevent a migration from running in a transaction by setting the
  137. ``atomic`` attribute to ``False``. For example::
  138. from django.db import migrations
  139. class Migration(migrations.Migration):
  140. atomic = False
  141. It's also possible to execute parts of the migration inside a transaction using
  142. :func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to
  143. :class:`~django.db.migrations.operations.RunPython`. See
  144. :ref:`non-atomic-migrations` for more details.
  145. Dependencies
  146. ============
  147. While migrations are per-app, the tables and relationships implied by
  148. your models are too complex to be created for one app at a time. When you make
  149. a migration that requires something else to run - for example, you add a
  150. ``ForeignKey`` in your ``books`` app to your ``authors`` app - the resulting
  151. migration will contain a dependency on a migration in ``authors``.
  152. This means that when you run the migrations, the ``authors`` migration runs
  153. first and creates the table the ``ForeignKey`` references, and then the migration
  154. that makes the ``ForeignKey`` column runs afterward and creates the constraint.
  155. If this didn't happen, the migration would try to create the ``ForeignKey``
  156. column without the table it's referencing existing and your database would
  157. throw an error.
  158. This dependency behavior affects most migration operations where you
  159. restrict to a single app. Restricting to a single app (either in
  160. ``makemigrations`` or ``migrate``) is a best-efforts promise, and not
  161. a guarantee; any other apps that need to be used to get dependencies correct
  162. will be.
  163. Apps without migrations must not have relations (``ForeignKey``,
  164. ``ManyToManyField``, etc.) to apps with migrations. Sometimes it may work, but
  165. it's not supported.
  166. Swappable dependencies
  167. ----------------------
  168. .. function:: django.db.migrations.swappable_dependency(value)
  169. The ``swappable_dependency()`` function is used in migrations to declare
  170. "swappable" dependencies on migrations in the app of the swapped-in model,
  171. currently, on the first migration of this app. As a consequence, the swapped-in
  172. model should be created in the initial migration. The argument ``value`` is a
  173. string ``"<app label>.<model>"`` describing an app label and a model name, e.g.
  174. ``"myapp.MyModel"``.
  175. By using ``swappable_dependency()``, you inform the migration framework that
  176. the migration relies on another migration which sets up a swappable model,
  177. allowing for the possibility of substituting the model with a different
  178. implementation in the future. This is typically used for referencing models
  179. that are subject to customization or replacement, such as the custom user
  180. model (``settings.AUTH_USER_MODEL``, which defaults to ``"auth.User"``) in
  181. Django's authentication system.
  182. .. _migration-files:
  183. Migration files
  184. ===============
  185. Migrations are stored as an on-disk format, referred to here as
  186. "migration files". These files are actually normal Python files with an
  187. agreed-upon object layout, written in a declarative style.
  188. A basic migration file looks like this::
  189. from django.db import migrations, models
  190. class Migration(migrations.Migration):
  191. dependencies = [("migrations", "0001_initial")]
  192. operations = [
  193. migrations.DeleteModel("Tribble"),
  194. migrations.AddField("Author", "rating", models.IntegerField(default=0)),
  195. ]
  196. What Django looks for when it loads a migration file (as a Python module) is
  197. a subclass of ``django.db.migrations.Migration`` called ``Migration``. It then
  198. inspects this object for four attributes, only two of which are used
  199. most of the time:
  200. * ``dependencies``, a list of migrations this one depends on.
  201. * ``operations``, a list of ``Operation`` classes that define what this
  202. migration does.
  203. The operations are the key; they are a set of declarative instructions which
  204. tell Django what schema changes need to be made. Django scans them and
  205. builds an in-memory representation of all of the schema changes to all apps,
  206. and uses this to generate the SQL which makes the schema changes.
  207. That in-memory structure is also used to work out what the differences are
  208. between your models and the current state of your migrations; Django runs
  209. through all the changes, in order, on an in-memory set of models to come
  210. up with the state of your models last time you ran ``makemigrations``. It
  211. then uses these models to compare against the ones in your ``models.py`` files
  212. to work out what you have changed.
  213. You should rarely, if ever, need to edit migration files by hand, but
  214. it's entirely possible to write them manually if you need to. Some of the
  215. more complex operations are not autodetectable and are only available via
  216. a hand-written migration, so don't be scared about editing them if you have to.
  217. Custom fields
  218. -------------
  219. You can't modify the number of positional arguments in an already migrated
  220. custom field without raising a ``TypeError``. The old migration will call the
  221. modified ``__init__`` method with the old signature. So if you need a new
  222. argument, please create a keyword argument and add something like
  223. ``assert 'argument_name' in kwargs`` in the constructor.
  224. .. _using-managers-in-migrations:
  225. Model managers
  226. --------------
  227. You can optionally serialize managers into migrations and have them available
  228. in :class:`~django.db.migrations.operations.RunPython` operations. This is done
  229. by defining a ``use_in_migrations`` attribute on the manager class::
  230. class MyManager(models.Manager):
  231. use_in_migrations = True
  232. class MyModel(models.Model):
  233. objects = MyManager()
  234. If you are using the :meth:`~django.db.models.from_queryset` function to
  235. dynamically generate a manager class, you need to inherit from the generated
  236. class to make it importable::
  237. class MyManager(MyBaseManager.from_queryset(CustomQuerySet)):
  238. use_in_migrations = True
  239. class MyModel(models.Model):
  240. objects = MyManager()
  241. Please refer to the notes about :ref:`historical-models` in migrations to see
  242. the implications that come along.
  243. Initial migrations
  244. ------------------
  245. .. attribute:: Migration.initial
  246. The "initial migrations" for an app are the migrations that create the first
  247. version of that app's tables. Usually an app will have one initial migration,
  248. but in some cases of complex model interdependencies it may have two or more.
  249. Initial migrations are marked with an ``initial = True`` class attribute on the
  250. migration class. If an ``initial`` class attribute isn't found, a migration
  251. will be considered "initial" if it is the first migration in the app (i.e. if
  252. it has no dependencies on any other migration in the same app).
  253. When the :option:`migrate --fake-initial` option is used, these initial
  254. migrations are treated specially. For an initial migration that creates one or
  255. more tables (``CreateModel`` operation), Django checks that all of those tables
  256. already exist in the database and fake-applies the migration if so. Similarly,
  257. for an initial migration that adds one or more fields (``AddField`` operation),
  258. Django checks that all of the respective columns already exist in the database
  259. and fake-applies the migration if so. Without ``--fake-initial``, initial
  260. migrations are treated no differently from any other migration.
  261. .. _migration-history-consistency:
  262. History consistency
  263. -------------------
  264. As previously discussed, you may need to linearize migrations manually when two
  265. development branches are joined. While editing migration dependencies, you can
  266. inadvertently create an inconsistent history state where a migration has been
  267. applied but some of its dependencies haven't. This is a strong indication that
  268. the dependencies are incorrect, so Django will refuse to run migrations or make
  269. new migrations until it's fixed. When using multiple databases, you can use the
  270. :meth:`allow_migrate` method of :ref:`database routers
  271. <topics-db-multi-db-routing>` to control which databases
  272. :djadmin:`makemigrations` checks for consistent history.
  273. Adding migrations to apps
  274. =========================
  275. New apps come preconfigured to accept migrations, and so you can add migrations
  276. by running :djadmin:`makemigrations` once you've made some changes.
  277. If your app already has models and database tables, and doesn't have migrations
  278. yet (for example, you created it against a previous Django version), you'll
  279. need to convert it to use migrations by running:
  280. .. code-block:: shell
  281. $ python manage.py makemigrations your_app_label
  282. This will make a new initial migration for your app. Now, run ``python
  283. manage.py migrate --fake-initial``, and Django will detect that you have an
  284. initial migration *and* that the tables it wants to create already exist, and
  285. will mark the migration as already applied. (Without the :option:`migrate
  286. --fake-initial` flag, the command would error out because the tables it wants
  287. to create already exist.)
  288. Note that this only works given two things:
  289. * You have not changed your models since you made their tables. For migrations
  290. to work, you must make the initial migration *first* and then make changes,
  291. as Django compares changes against migration files, not the database.
  292. * You have not manually edited your database - Django won't be able to detect
  293. that your database doesn't match your models, you'll just get errors when
  294. migrations try to modify those tables.
  295. .. _reversing-migrations:
  296. Reversing migrations
  297. ====================
  298. Migrations can be reversed with :djadmin:`migrate` by passing the number of the
  299. previous migration. For example, to reverse migration ``books.0003``:
  300. .. console::
  301. $ python manage.py migrate books 0002
  302. Operations to perform:
  303. Target specific migration: 0002_auto, from books
  304. Running migrations:
  305. Rendering model states... DONE
  306. Unapplying books.0003_auto... OK
  307. If you want to reverse all migrations applied for an app, use the name
  308. ``zero``:
  309. .. console::
  310. $ python manage.py migrate books zero
  311. Operations to perform:
  312. Unapply all migrations: books
  313. Running migrations:
  314. Rendering model states... DONE
  315. Unapplying books.0002_auto... OK
  316. Unapplying books.0001_initial... OK
  317. A migration is irreversible if it contains any irreversible operations.
  318. Attempting to reverse such migrations will raise ``IrreversibleError``:
  319. .. console::
  320. $ python manage.py migrate books 0002
  321. Operations to perform:
  322. Target specific migration: 0002_auto, from books
  323. Running migrations:
  324. Rendering model states... DONE
  325. Unapplying books.0003_auto...Traceback (most recent call last):
  326. django.db.migrations.exceptions.IrreversibleError: Operation <RunSQL sql='DROP TABLE demo_books'> in books.0003_auto is not reversible
  327. .. _historical-models:
  328. Historical models
  329. =================
  330. When you run migrations, Django is working from historical versions of your
  331. models stored in the migration files. If you write Python code using the
  332. :class:`~django.db.migrations.operations.RunPython` operation, or if you have
  333. ``allow_migrate`` methods on your database routers, you **need to use** these
  334. historical model versions rather than importing them directly.
  335. .. warning::
  336. If you import models directly rather than using the historical models,
  337. your migrations *may work initially* but will fail in the future when you
  338. try to rerun old migrations (commonly, when you set up a new installation
  339. and run through all the migrations to set up the database).
  340. This means that historical model problems may not be immediately obvious.
  341. If you run into this kind of failure, it's OK to edit the migration to use
  342. the historical models rather than direct imports and commit those changes.
  343. Because it's impossible to serialize arbitrary Python code, these historical
  344. models will not have any custom methods that you have defined. They will,
  345. however, have the same fields, relationships, managers (limited to those with
  346. ``use_in_migrations = True``) and ``Meta`` options (also versioned, so they may
  347. be different from your current ones).
  348. .. warning::
  349. This means that you will NOT have custom ``save()`` methods called on objects
  350. when you access them in migrations, and you will NOT have any custom
  351. constructors or instance methods. Plan appropriately!
  352. References to functions in field options such as ``upload_to`` and
  353. ``limit_choices_to`` and model manager declarations with managers having
  354. ``use_in_migrations = True`` are serialized in migrations, so the functions and
  355. classes will need to be kept around for as long as there is a migration
  356. referencing them. Any :doc:`custom model fields </howto/custom-model-fields>`
  357. will also need to be kept, since these are imported directly by migrations.
  358. In addition, the concrete base classes of the model are stored as pointers, so
  359. you must always keep base classes around for as long as there is a migration
  360. that contains a reference to them. On the plus side, methods and managers from
  361. these base classes inherit normally, so if you absolutely need access to these
  362. you can opt to move them into a superclass.
  363. To remove old references, you can :ref:`squash migrations <migration-squashing>`
  364. or, if there aren't many references, copy them into the migration files.
  365. .. _migrations-removing-model-fields:
  366. Considerations when removing model fields
  367. =========================================
  368. Similar to the "references to historical functions" considerations described in
  369. the previous section, removing custom model fields from your project or
  370. third-party app will cause a problem if they are referenced in old migrations.
  371. To help with this situation, Django provides some model field attributes to
  372. assist with model field deprecation using the :doc:`system checks framework
  373. </topics/checks>`.
  374. Add the ``system_check_deprecated_details`` attribute to your model field
  375. similar to the following::
  376. class IPAddressField(Field):
  377. system_check_deprecated_details = {
  378. "msg": (
  379. "IPAddressField has been deprecated. Support for it (except "
  380. "in historical migrations) will be removed in Django 1.9."
  381. ),
  382. "hint": "Use GenericIPAddressField instead.", # optional
  383. "id": "fields.W900", # pick a unique ID for your field.
  384. }
  385. After a deprecation period of your choosing (two or three feature releases for
  386. fields in Django itself), change the ``system_check_deprecated_details``
  387. attribute to ``system_check_removed_details`` and update the dictionary similar
  388. to::
  389. class IPAddressField(Field):
  390. system_check_removed_details = {
  391. "msg": (
  392. "IPAddressField has been removed except for support in "
  393. "historical migrations."
  394. ),
  395. "hint": "Use GenericIPAddressField instead.",
  396. "id": "fields.E900", # pick a unique ID for your field.
  397. }
  398. You should keep the field's methods that are required for it to operate in
  399. database migrations such as ``__init__()``, ``deconstruct()``, and
  400. ``get_internal_type()``. Keep this stub field for as long as any migrations
  401. which reference the field exist. For example, after squashing migrations and
  402. removing the old ones, you should be able to remove the field completely.
  403. .. _data-migrations:
  404. Data Migrations
  405. ===============
  406. As well as changing the database schema, you can also use migrations to change
  407. the data in the database itself, in conjunction with the schema if you want.
  408. Migrations that alter data are usually called "data migrations"; they're best
  409. written as separate migrations, sitting alongside your schema migrations.
  410. Django can't automatically generate data migrations for you, as it does with
  411. schema migrations, but it's not very hard to write them. Migration files in
  412. Django are made up of :doc:`Operations </ref/migration-operations>`, and
  413. the main operation you use for data migrations is
  414. :class:`~django.db.migrations.operations.RunPython`.
  415. To start, make an empty migration file you can work from (Django will put
  416. the file in the right place, suggest a name, and add dependencies for you):
  417. .. code-block:: shell
  418. python manage.py makemigrations --empty yourappname
  419. Then, open up the file; it should look something like this::
  420. # Generated by Django A.B on YYYY-MM-DD HH:MM
  421. from django.db import migrations
  422. class Migration(migrations.Migration):
  423. dependencies = [
  424. ("yourappname", "0001_initial"),
  425. ]
  426. operations = []
  427. Now, all you need to do is create a new function and have
  428. :class:`~django.db.migrations.operations.RunPython` use it.
  429. :class:`~django.db.migrations.operations.RunPython` expects a callable as its argument
  430. which takes two arguments - the first is an :doc:`app registry
  431. </ref/applications/>` that has the historical versions of all your models
  432. loaded into it to match where in your history the migration sits, and the
  433. second is a :doc:`SchemaEditor </ref/schema-editor>`, which you can use to
  434. manually effect database schema changes (but beware, doing this can confuse
  435. the migration autodetector!)
  436. Let's write a migration that populates our new ``name`` field with the combined
  437. values of ``first_name`` and ``last_name`` (we've come to our senses and
  438. realized that not everyone has first and last names). All we need to do is use
  439. the historical model and iterate over the rows::
  440. from django.db import migrations
  441. def combine_names(apps, schema_editor):
  442. # We can't import the Person model directly as it may be a newer
  443. # version than this migration expects. We use the historical version.
  444. Person = apps.get_model("yourappname", "Person")
  445. for person in Person.objects.all():
  446. person.name = f"{person.first_name} {person.last_name}"
  447. person.save()
  448. class Migration(migrations.Migration):
  449. dependencies = [
  450. ("yourappname", "0001_initial"),
  451. ]
  452. operations = [
  453. migrations.RunPython(combine_names),
  454. ]
  455. Once that's done, we can run ``python manage.py migrate`` as normal and the
  456. data migration will run in place alongside other migrations.
  457. You can pass a second callable to
  458. :class:`~django.db.migrations.operations.RunPython` to run whatever logic you
  459. want executed when migrating backwards. If this callable is omitted, migrating
  460. backwards will raise an exception.
  461. Accessing models from other apps
  462. --------------------------------
  463. When writing a ``RunPython`` function that uses models from apps other than the
  464. one in which the migration is located, the migration's ``dependencies``
  465. attribute should include the latest migration of each app that is involved,
  466. otherwise you may get an error similar to: ``LookupError: No installed app
  467. with label 'myappname'`` when you try to retrieve the model in the ``RunPython``
  468. function using ``apps.get_model()``.
  469. In the following example, we have a migration in ``app1`` which needs to use
  470. models in ``app2``. We aren't concerned with the details of ``move_m1`` other
  471. than the fact it will need to access models from both apps. Therefore we've
  472. added a dependency that specifies the last migration of ``app2``::
  473. class Migration(migrations.Migration):
  474. dependencies = [
  475. ("app1", "0001_initial"),
  476. # added dependency to enable using models from app2 in move_m1
  477. ("app2", "0004_foobar"),
  478. ]
  479. operations = [
  480. migrations.RunPython(move_m1),
  481. ]
  482. More advanced migrations
  483. ------------------------
  484. If you're interested in the more advanced migration operations, or want
  485. to be able to write your own, see the :doc:`migration operations reference
  486. </ref/migration-operations>` and the "how-to" on :doc:`writing migrations
  487. </howto/writing-migrations>`.
  488. .. _migration-squashing:
  489. Squashing migrations
  490. ====================
  491. You are encouraged to make migrations freely and not worry about how many you
  492. have; the migration code is optimized to deal with hundreds at a time without
  493. much slowdown. However, eventually you will want to move back from having
  494. several hundred migrations to just a few, and that's where squashing comes in.
  495. Squashing is the act of reducing an existing set of many migrations down to
  496. one (or sometimes a few) migrations which still represent the same changes.
  497. Django does this by taking all of your existing migrations, extracting their
  498. ``Operation``\s and putting them all in sequence, and then running an optimizer
  499. over them to try and reduce the length of the list - for example, it knows
  500. that :class:`~django.db.migrations.operations.CreateModel` and
  501. :class:`~django.db.migrations.operations.DeleteModel` cancel each other out,
  502. and it knows that :class:`~django.db.migrations.operations.AddField` can be
  503. rolled into :class:`~django.db.migrations.operations.CreateModel`.
  504. Once the operation sequence has been reduced as much as possible - the amount
  505. possible depends on how closely intertwined your models are and if you have
  506. any :class:`~django.db.migrations.operations.RunSQL`
  507. or :class:`~django.db.migrations.operations.RunPython` operations (which can't
  508. be optimized through unless they are marked as ``elidable``) - Django will then
  509. write it back out into a new set of migration files.
  510. These files are marked to say they replace the previously-squashed migrations,
  511. so they can coexist with the old migration files, and Django will intelligently
  512. switch between them depending where you are in the history. If you're still
  513. part-way through the set of migrations that you squashed, it will keep using
  514. them until it hits the end and then switch to the squashed history, while new
  515. installs will use the new squashed migration and skip all the old ones.
  516. This enables you to squash and not mess up systems currently in production
  517. that aren't fully up-to-date yet. The recommended process is to squash, keeping
  518. the old files, commit and release, wait until all systems are upgraded with
  519. the new release (or if you're a third-party project, ensure your users upgrade
  520. releases in order without skipping any), and then remove the old files, commit
  521. and do a second release.
  522. The command that backs all this is :djadmin:`squashmigrations` - pass it the
  523. app label and migration name you want to squash up to, and it'll get to work:
  524. .. code-block:: shell
  525. $ ./manage.py squashmigrations myapp 0004
  526. Will squash the following migrations:
  527. - 0001_initial
  528. - 0002_some_change
  529. - 0003_another_change
  530. - 0004_undo_something
  531. Do you wish to proceed? [y/N] y
  532. Optimizing...
  533. Optimized from 12 operations to 7 operations.
  534. Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py
  535. You should commit this migration but leave the old ones in place;
  536. the new migration will be used for new installs. Once you are sure
  537. all instances of the codebase have applied the migrations you squashed,
  538. you can delete them.
  539. Use the :option:`squashmigrations --squashed-name` option if you want to set
  540. the name of the squashed migration rather than use an autogenerated one.
  541. Note that model interdependencies in Django can get very complex, and squashing
  542. may result in migrations that do not run; either mis-optimized (in which case
  543. you can try again with ``--no-optimize``, though you should also report an issue),
  544. or with a ``CircularDependencyError``, in which case you can manually resolve it.
  545. To manually resolve a ``CircularDependencyError``, break out one of
  546. the ForeignKeys in the circular dependency loop into a separate
  547. migration, and move the dependency on the other app with it. If you're unsure,
  548. see how :djadmin:`makemigrations` deals with the problem when asked to create
  549. brand new migrations from your models. In a future release of Django,
  550. :djadmin:`squashmigrations` will be updated to attempt to resolve these errors
  551. itself.
  552. Once you've squashed your migration, you should then commit it alongside the
  553. migrations it replaces and distribute this change to all running instances
  554. of your application, making sure that they run ``migrate`` to store the change
  555. in their database.
  556. You must then transition the squashed migration to a normal migration by:
  557. - Deleting all the migration files it replaces.
  558. - Updating all migrations that depend on the deleted migrations to depend on
  559. the squashed migration instead.
  560. - Removing the ``replaces`` attribute in the ``Migration`` class of the
  561. squashed migration (this is how Django tells that it is a squashed migration).
  562. .. note::
  563. Once you've squashed a migration, you should not then re-squash that squashed
  564. migration until you have fully transitioned it to a normal migration.
  565. .. admonition:: Pruning references to deleted migrations
  566. If it is likely that you may reuse the name of a deleted migration in the
  567. future, you should remove references to it from Django’s migrations table
  568. with the :option:`migrate --prune` option.
  569. .. _migration-serializing:
  570. Serializing values
  571. ==================
  572. Migrations are Python files containing the old definitions of your models
  573. - thus, to write them, Django must take the current state of your models and
  574. serialize them out into a file.
  575. While Django can serialize most things, there are some things that we just
  576. can't serialize out into a valid Python representation - there's no Python
  577. standard for how a value can be turned back into code (``repr()`` only works
  578. for basic values, and doesn't specify import paths).
  579. Django can serialize the following:
  580. - ``int``, ``float``, ``bool``, ``str``, ``bytes``, ``None``, ``NoneType``
  581. - ``list``, ``set``, ``tuple``, ``dict``, ``range``.
  582. - ``datetime.date``, ``datetime.time``, and ``datetime.datetime`` instances
  583. (include those that are timezone-aware)
  584. - ``decimal.Decimal`` instances
  585. - ``enum.Enum`` and ``enum.Flag`` instances
  586. - ``uuid.UUID`` instances
  587. - :func:`functools.partial` and :class:`functools.partialmethod` instances
  588. which have serializable ``func``, ``args``, and ``keywords`` values.
  589. - Pure and concrete path objects from :mod:`pathlib`. Concrete paths are
  590. converted to their pure path equivalent, e.g. :class:`pathlib.PosixPath` to
  591. :class:`pathlib.PurePosixPath`.
  592. - :class:`os.PathLike` instances, e.g. :class:`os.DirEntry`, which are
  593. converted to ``str`` or ``bytes`` using :func:`os.fspath`.
  594. - ``LazyObject`` instances which wrap a serializable value.
  595. - Enumeration types (e.g. ``TextChoices`` or ``IntegerChoices``) instances.
  596. - Any Django field
  597. - Any function or method reference (e.g. ``datetime.datetime.today``) (must be
  598. in module's top-level scope)
  599. - Functions may be decorated if wrapped properly, i.e. using
  600. :func:`functools.wraps`
  601. - The :func:`functools.cache` and :func:`functools.lru_cache` decorators are
  602. explicitly supported
  603. - Unbound methods used from within the class body
  604. - Any class reference (must be in module's top-level scope)
  605. - Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`)
  606. Django cannot serialize:
  607. - Nested classes
  608. - Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)
  609. - Lambdas
  610. .. _custom-migration-serializers:
  611. Custom serializers
  612. ------------------
  613. You can serialize other types by writing a custom serializer. For example, if
  614. Django didn't serialize :class:`~decimal.Decimal` by default, you could do
  615. this::
  616. from decimal import Decimal
  617. from django.db.migrations.serializer import BaseSerializer
  618. from django.db.migrations.writer import MigrationWriter
  619. class DecimalSerializer(BaseSerializer):
  620. def serialize(self):
  621. return repr(self.value), {"from decimal import Decimal"}
  622. MigrationWriter.register_serializer(Decimal, DecimalSerializer)
  623. The first argument of ``MigrationWriter.register_serializer()`` is a type or
  624. iterable of types that should use the serializer.
  625. The ``serialize()`` method of your serializer must return a string of how the
  626. value should appear in migrations and a set of any imports that are needed in
  627. the migration.
  628. .. _custom-deconstruct-method:
  629. Adding a ``deconstruct()`` method
  630. ---------------------------------
  631. You can let Django serialize your own custom class instances by giving the class
  632. a ``deconstruct()`` method. It takes no arguments, and should return a tuple
  633. of three things ``(path, args, kwargs)``:
  634. * ``path`` should be the Python path to the class, with the class name included
  635. as the last part (for example, ``myapp.custom_things.MyClass``). If your
  636. class is not available at the top level of a module it is not serializable.
  637. * ``args`` should be a list of positional arguments to pass to your class'
  638. ``__init__`` method. Everything in this list should itself be serializable.
  639. * ``kwargs`` should be a dict of keyword arguments to pass to your class'
  640. ``__init__`` method. Every value should itself be serializable.
  641. .. note::
  642. This return value is different from the ``deconstruct()`` method
  643. :ref:`for custom fields <custom-field-deconstruct-method>` which returns a
  644. tuple of four items.
  645. Django will write out the value as an instantiation of your class with the
  646. given arguments, similar to the way it writes out references to Django fields.
  647. To prevent a new migration from being created each time
  648. :djadmin:`makemigrations` is run, you should also add a ``__eq__()`` method to
  649. the decorated class. This function will be called by Django's migration
  650. framework to detect changes between states.
  651. As long as all of the arguments to your class' constructor are themselves
  652. serializable, you can use the ``@deconstructible`` class decorator from
  653. ``django.utils.deconstruct`` to add the ``deconstruct()`` method::
  654. from django.utils.deconstruct import deconstructible
  655. @deconstructible
  656. class MyCustomClass:
  657. def __init__(self, foo=1):
  658. self.foo = foo
  659. ...
  660. def __eq__(self, other):
  661. return self.foo == other.foo
  662. The decorator adds logic to capture and preserve the arguments on their
  663. way into your constructor, and then returns those arguments exactly when
  664. deconstruct() is called.
  665. Supporting multiple Django versions
  666. ===================================
  667. If you are the maintainer of a third-party app with models, you may need to
  668. ship migrations that support multiple Django versions. In this case, you should
  669. always run :djadmin:`makemigrations` **with the lowest Django version you wish
  670. to support**.
  671. The migrations system will maintain backwards-compatibility according to the
  672. same policy as the rest of Django, so migration files generated on Django X.Y
  673. should run unchanged on Django X.Y+1. The migrations system does not promise
  674. forwards-compatibility, however. New features may be added, and migration files
  675. generated with newer versions of Django may not work on older versions.
  676. .. seealso::
  677. :doc:`The Migrations Operations Reference </ref/migration-operations>`
  678. Covers the schema operations API, special operations, and writing your
  679. own operations.
  680. :doc:`The Writing Migrations "how-to" </howto/writing-migrations>`
  681. Explains how to structure and write database migrations for different
  682. scenarios you might encounter.