migrations.txt 33 KB

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