migrations.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. ==========
  2. Migrations
  3. ==========
  4. .. module:: django.db.migrations
  5. :synopsis: Schema migration support for Django models
  6. .. versionadded:: 1.7
  7. Migrations are Django's way of propagating changes you make to your models
  8. (adding a field, deleting a model, etc.) into your database schema. They're
  9. designed to be mostly automatic, but you'll need to know when to make
  10. migrations, when to run them, and the common problems you might run into.
  11. A Brief History
  12. ---------------
  13. Prior to version 1.7, Django only supported adding new models to the
  14. database; it was not possible to alter or remove existing models via the
  15. ``syncdb`` command (the predecessor to :djadmin:`migrate`).
  16. Third-party tools, most notably `South <http://south.aeracode.org>`_,
  17. provided support for these additional types of change, but it was considered
  18. important enough that support was brought into core Django.
  19. Two Commands
  20. ------------
  21. There are two commands which you will use to interact with migrations
  22. and Django's handling of database schema:
  23. * :djadmin:`migrate`, which is responsible for applying migrations, as well as
  24. unapplying and listing their status.
  25. * :djadmin:`makemigrations`, which is responsible for creating new migrations
  26. based on the changes you have made to your models.
  27. It's worth noting that migrations are created and run on a per-app basis.
  28. In particular, it's possible to have apps that *do not use migrations* (these
  29. are referred to as "unmigrated" apps) - these apps will instead mimic the
  30. legacy behavior of just adding new models.
  31. You should think of migrations as a version control system for your database
  32. schema. ``makemigrations`` is responsible for packaging up your model changes
  33. into individual migration files - analogous to commits - and ``migrate`` is
  34. responsible for applying those to your database.
  35. The migration files for each app live in a "migrations" directory inside
  36. of that app, and are designed to be committed to, and distributed as part
  37. of, its codebase. You should be making them once on your development machine
  38. and then running the same migrations on your colleagues' machines, your
  39. staging machines, and eventually your production machines.
  40. .. note::
  41. It is possible to override the name of the package which contains the
  42. migrations on a per-app basis by modifying the :setting:`MIGRATION_MODULES`
  43. setting.
  44. Migrations will run the same way on the same dataset and produce consistent
  45. results, meaning that what you see in development and staging is, under the
  46. same circumstances, exactly what will happen in production.
  47. Backend Support
  48. ---------------
  49. Migrations are supported on all backends that Django ships with, as well
  50. as any third-party backends if they have programmed in support for schema
  51. alteration (done via the :doc:`SchemaEditor </ref/schema-editor>` class).
  52. However, some databases are more capable than others when it comes to
  53. schema migrations; some of the caveats are covered below.
  54. PostgreSQL
  55. ~~~~~~~~~~
  56. PostgreSQL is the most capable of all the databases here in terms of schema
  57. support; the only caveat is that adding columns with default values will
  58. cause a full rewrite of the table, for a time proportional to its size.
  59. For this reason, it's recommended you always create new columns with
  60. ``null=True``, as this way they will be added immediately.
  61. MySQL
  62. ~~~~~
  63. MySQL lacks support for transactions around schema alteration operations,
  64. meaning that if a migration fails to apply you will have to manually unpick
  65. the changes in order to try again (it's impossible to roll back to an
  66. earlier point).
  67. In addition, MySQL will fully rewrite tables for almost every schema operation
  68. and generally takes a time proportional to the number of rows in the table to
  69. add or remove columns. On slower hardware this can be worse than a minute per
  70. million rows - adding a few columns to a table with just a few million rows
  71. could lock your site up for over ten minutes.
  72. Finally, MySQL has reasonably small limits on name lengths for columns, tables
  73. and indexes, as well as a limit on the combined size of all columns an index
  74. covers. This means that indexes that are possible on other backends will
  75. fail to be created under MySQL.
  76. SQLite
  77. ~~~~~~
  78. SQLite has very little built-in schema alteration support, and so Django
  79. attempts to emulate it by:
  80. * Creating a new table with the new schema
  81. * Copying the data across
  82. * Dropping the old table
  83. * Renaming the new table to match the original name
  84. This process generally works well, but it can be slow and occasionally
  85. buggy. It is not recommended that you run and migrate SQLite in a
  86. production environment unless you are very aware of the risks and
  87. its limitations; the support Django ships with is designed to allow
  88. developers to use SQLite on their local machines to develop less complex
  89. Django projects without the need for a full database.
  90. Workflow
  91. --------
  92. Working with migrations is simple. Make changes to your models - say, add
  93. a field and remove a model - and then run :djadmin:`makemigrations`::
  94. $ python manage.py makemigrations
  95. Migrations for 'books':
  96. 0003_auto.py:
  97. - Alter field author on book
  98. Your models will be scanned and compared to the versions currently
  99. contained in your migration files, and then a new set of migrations
  100. will be written out. Make sure to read the output to see what
  101. ``makemigrations`` thinks you have changed - it's not perfect, and for
  102. complex changes it might not be detecting what you expect.
  103. Once you have your new migration files, you should apply them to your
  104. database to make sure they work as expected::
  105. $ python manage.py migrate
  106. Operations to perform:
  107. Synchronize unmigrated apps: sessions, admin, messages, auth, staticfiles, contenttypes
  108. Apply all migrations: books
  109. Synchronizing apps without migrations:
  110. Creating tables...
  111. Installing custom SQL...
  112. Installing indexes...
  113. Installed 0 object(s) from 0 fixture(s)
  114. Running migrations:
  115. Applying books.0003_auto... OK
  116. The command runs in two stages; first, it synchronizes unmigrated apps
  117. (performing the same functionality that ``syncdb`` used to provide), and
  118. then it runs any migrations that have not yet been applied.
  119. Once the migration is applied, commit the migration and the models change
  120. to your version control system as a single commit - that way, when other
  121. developers (or your production servers) check out the code, they'll
  122. get both the changes to your models and the accompanying migration at the
  123. same time.
  124. Version control
  125. ~~~~~~~~~~~~~~~
  126. Because migrations are stored in version control, you'll occasionally
  127. come across situations where you and another developer have both committed
  128. a migration to the same app at the same time, resulting in two migrations
  129. with the same number.
  130. Don't worry - the numbers are just there for developers' reference, Django
  131. just cares that each migration has a different name. Migrations specify which
  132. other migrations they depend on - including earlier migrations in the same
  133. app - in the file, so it's possible to detect when there's two new migrations
  134. for the same app that aren't ordered.
  135. When this happens, Django will prompt you and give you some options. If it
  136. thinks it's safe enough, it will offer to automatically linearize the two
  137. migrations for you. If not, you'll have to go in and modify the migrations
  138. yourself - don't worry, this isn't difficult, and is explained more in
  139. :ref:`migration-files` below.
  140. Dependencies
  141. ------------
  142. While migrations are per-app, the tables and relationships implied by
  143. your models are too complex to be created for just one app at a time. When
  144. you make a migration that requires something else to run - for example,
  145. you add a ``ForeignKey`` in your ``books`` app to your ``authors`` app - the
  146. resulting migration will contain a dependency on a migration in ``authors``.
  147. This means that when you run the migrations, the ``authors`` migration runs
  148. first and creates the table the ``ForeignKey`` references, and then the migration
  149. that makes the ``ForeignKey`` column runs afterwards and creates the constraint.
  150. If this didn't happen, the migration would try to create the ``ForeignKey``
  151. column without the table it's referencing existing and your database would
  152. throw an error.
  153. This dependency behavior affects most migration operations where you
  154. restrict to a single app. Restricting to a single app (either in
  155. ``makemigrations`` or ``migrate``) is a best-efforts promise, and not
  156. a guarantee; any other apps that need to be used to get dependencies correct
  157. will be.
  158. .. _migration-files:
  159. Migration files
  160. ---------------
  161. Migrations are stored as an on-disk format, referred to here as
  162. "migration files". These files are actually just normal Python files with
  163. an agreed-upon object layout, written in a declarative style.
  164. A basic migration file looks like this::
  165. from django.db import migrations, models
  166. class Migration(migrations.Migration):
  167. dependencies = [("migrations", "0001_initial")]
  168. operations = [
  169. migrations.DeleteModel("Tribble"),
  170. migrations.AddField("Author", "rating", models.IntegerField(default=0)),
  171. ]
  172. What Django looks for when it loads a migration file (as a Python module) is
  173. a subclass of ``django.db.migrations.Migration`` called ``Migration``. It then
  174. inspects this object for four attributes, only two of which are used
  175. most of the time:
  176. * ``dependencies``, a list of migrations this one depends on.
  177. * ``operations``, a list of ``Operation`` classes that define what this
  178. migration does.
  179. The operations are the key; they are a set of declarative instructions which
  180. tell Django what schema changes need to be made. Django scans them and
  181. builds an in-memory representation of all of the schema changes to all apps,
  182. and uses this to generate the SQL which makes the schema changes.
  183. That in-memory structure is also used to work out what the differences are
  184. between your models and the current state of your migrations; Django runs
  185. through all the changes, in order, on an in-memory set of models to come
  186. up with the state of your models last time you ran ``makemigrations``. It
  187. then uses these models to compare against the ones in your ``models.py`` files
  188. to work out what you have changed.
  189. You should rarely, if ever, need to edit migration files by hand, but
  190. it's entirely possible to write them manually if you need to. Some of the
  191. more complex operations are not autodetectable and are only available via
  192. a hand-written migration, so don't be scared about editing them if you have to.
  193. Custom fields
  194. ~~~~~~~~~~~~~
  195. You can't modify the number of positional arguments in an already migrated
  196. custom field without raising a ``TypeError``. The old migration will call the
  197. modified ``__init__`` method with the old signature. So if you need a new
  198. argument, please create a keyword argument and add something like
  199. ``assert kwargs.get('argument_name') is not None`` in the constructor.
  200. Adding migrations to apps
  201. -------------------------
  202. Adding migrations to new apps is straightforward - they come preconfigured to
  203. accept migrations, and so just run :djadmin:`makemigrations` once you've made
  204. some changes.
  205. If your app already has models and database tables, and doesn't have migrations
  206. yet (for example, you created it against a previous Django version), you'll
  207. need to convert it to use migrations; this is a simple process::
  208. $ python manage.py makemigrations your_app_label
  209. This will make a new initial migration for your app. Now, when you run
  210. :djadmin:`migrate`, Django will detect that you have an initial migration
  211. *and* that the tables it wants to create already exist, and will mark the
  212. migration as already applied.
  213. Note that this only works given two things:
  214. * You have not changed your models since you made their tables. For migrations
  215. to work, you must make the initial migration *first* and then make changes,
  216. as Django compares changes against migration files, not the database.
  217. * You have not manually edited your database - Django won't be able to detect
  218. that your database doesn't match your models, you'll just get errors when
  219. migrations try to modify those tables.
  220. .. _historical-models:
  221. Historical models
  222. -----------------
  223. When you run migrations, Django is working from historical versions of
  224. your models stored in the migration files. If you write Python code
  225. using the :class:`~django.db.migrations.operations.RunPython` operation, or if
  226. you have ``allow_migrate`` methods on your database routers, you will be
  227. exposed to these versions of your models.
  228. Because it's impossible to serialize arbitrary Python code, these historical
  229. models will not have any custom methods or managers that you have defined.
  230. They will, however, have the same fields, relationships and ``Meta`` options
  231. (also versioned, so they may be different from your current ones).
  232. .. warning::
  233. This means that you will NOT have custom ``save()`` methods called on objects
  234. when you access them in migrations, and you will NOT have any custom
  235. constructors or instance methods. Plan appropriately!
  236. In addition, the base classes of the model are just stored as pointers,
  237. so you must always keep base classes around for as long as there is a migration
  238. that contains a reference to them. On the plus side, methods and managers
  239. from these base classes inherit normally, so if you absolutely need access
  240. to these you can opt to move them into a superclass.
  241. .. _data-migrations:
  242. Data Migrations
  243. ---------------
  244. As well as changing the database schema, you can also use migrations to change
  245. the data in the database itself, in conjunction with the schema if you want.
  246. Migrations that alter data are usually called "data migrations"; they're best
  247. written as separate migrations, sitting alongside your schema migrations.
  248. Django can't automatically generate data migrations for you, as it does with
  249. schema migrations, but it's not very hard to write them. Migration files in
  250. Django are made up of :doc:`Operations </ref/migration-operations>`, and
  251. the main operation you use for data migrations is
  252. :class:`~django.db.migrations.operations.RunPython`.
  253. To start, make an empty migration file you can work from (Django will put
  254. the file in the right place, suggest a name, and add dependencies for you)::
  255. python manage.py makemigrations --empty yourappname
  256. Then, open up the file; it should look something like this::
  257. # encoding: utf8
  258. from django.db import models, migrations
  259. class Migration(migrations.Migration):
  260. dependencies = [
  261. ('yourappname', '0001_initial'),
  262. ]
  263. operations = [
  264. ]
  265. Now, all you need to do is create a new function and have
  266. :class:`~django.db.migrations.operations.RunPython` use it.
  267. :class:`~django.db.migrations.operations.RunPython` expects a callable as its argument
  268. which takes two arguments - the first is an :doc:`app registry
  269. </ref/applications/>` that has the historical versions of all your models
  270. loaded into it to match where in your history the migration sits, and the
  271. second is a :doc:`SchemaEditor </ref/schema-editor>`, which you can use to
  272. manually effect database schema changes (but beware, doing this can confuse
  273. the migration autodetector!)
  274. Let's write a simple migration that populates our new ``name`` field with the
  275. combined values of ``first_name`` and ``last_name`` (we've come to our senses
  276. and realized that not everyone has first and last names). All we
  277. need to do is use the historical model and iterate over the rows::
  278. # encoding: utf8
  279. from django.db import models, migrations
  280. def combine_names(apps, schema_editor):
  281. # We can't import the Person model directly as it may be a newer
  282. # version than this migration expects. We use the historical version.
  283. Person = apps.get_model("yourappname", "Person")
  284. for person in Person.objects.all():
  285. person.name = "%s %s" % (person.first_name, person.last_name)
  286. person.save()
  287. class Migration(migrations.Migration):
  288. dependencies = [
  289. ('yourappname', '0001_initial'),
  290. ]
  291. operations = [
  292. migrations.RunPython(combine_names),
  293. ]
  294. Once that's done, we can just run ``python manage.py migrate`` as normal and
  295. the data migration will run in place alongside other migrations.
  296. If you're interested in the more advanced migration operations, or want
  297. to be able to write your own, see the :doc:`migration operations reference
  298. </ref/migration-operations>`.
  299. .. _migration-squashing:
  300. Squashing migrations
  301. --------------------
  302. You are encouraged to make migrations freely and not worry about how many you
  303. have; the migration code is optimized to deal with hundreds at a time without
  304. much slowdown. However, eventually you will want to move back from having
  305. several hundred migrations to just a few, and that's where squashing comes in.
  306. Squashing is the act of reducing an existing set of many migrations down to
  307. one (or sometimes a few) migrations which still represent the same changes.
  308. Django does this by taking all of your existing migrations, extracting their
  309. ``Operation``\s and putting them all in sequence, and then running an optimizer
  310. over them to try and reduce the length of the list - for example, it knows
  311. that :class:`~django.db.migrations.operations.CreateModel` and
  312. :class:`~django.db.migrations.operations.DeleteModel` cancel each other out,
  313. and it knows that :class:`~django.db.migrations.operations.AddField` can be
  314. rolled into :class:`~django.db.migrations.operations.CreateModel`.
  315. Once the operation sequence has been reduced as much as possible - the amount
  316. possible depends on how closely intertwined your models are and if you have
  317. any :class:`~django.db.migrations.operations.RunSQL`
  318. or :class:`~django.db.migrations.operations.RunPython` operations (which can't
  319. be optimized through) - Django will them write it back out into a new set of
  320. initial migration files.
  321. These files are marked to say they replace the previously-squashed migrations,
  322. so they can coexist with the old migration files, and Django will intelligently
  323. switch between them depending where you are in the history. If you're still
  324. part-way through the set of migrations that you squashed, it will keep using
  325. them until it hits the end and then switch to the squashed history, while new
  326. installs will just use the new squashed migration and skip all the old ones.
  327. This enables you to squash and not mess up systems currently in production
  328. that aren't fully up-to-date yet. The recommended process is to squash, keeping
  329. the old files, commit and release, wait until all systems are upgraded with
  330. the new release (or if you're a third-party project, just ensure your users
  331. upgrade releases in order without skipping any), and then remove the old files,
  332. commit and do a second release.
  333. The command that backs all this is :djadmin:`squashmigrations` - just pass
  334. it the app label and migration name you want to squash up to, and it'll get to
  335. work::
  336. $ ./manage.py squashmigrations myapp 0004
  337. Will squash the following migrations:
  338. - 0001_initial
  339. - 0002_some_change
  340. - 0003_another_change
  341. - 0004_undo_something
  342. Do you wish to proceed? [yN] y
  343. Optimizing...
  344. Optimized from 12 operations to 7 operations.
  345. Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py
  346. You should commit this migration but leave the old ones in place;
  347. the new migration will be used for new installs. Once you are sure
  348. all instances of the codebase have applied the migrations you squashed,
  349. you can delete them.
  350. Note that model interdependencies in Django can get very complex, and squashing
  351. may occasionally result in an optimized migration that doesn't work or is
  352. impossible to run. When this occurs, you can re-try with ``--no-optimize``, but
  353. please `file a bug report <https://code.djangoproject.com/newticket>`_ either
  354. way detailing the models and their relationships so we can improve the
  355. optimizer to handle your case.
  356. .. _migration-serializing:
  357. Serializing values
  358. ------------------
  359. Migrations are just Python files containing the old definitions of your models
  360. - thus, to write them, Django must take the current state of your models and
  361. serialize them out into a file.
  362. While Django can serialize most things, there are some things that we just
  363. can't serialize out into a valid Python representation - there's no Python
  364. standard for how a value can be turned back into code (``repr()`` only works
  365. for basic values, and doesn't specify import paths).
  366. Django can serialize the following:
  367. - ``int``, ``long``, ``float``, ``bool``, ``str``, ``unicode``, ``bytes``, ``None``
  368. - ``list``, ``set``, ``tuple``, ``dict``
  369. - ``datetime.date`` and ``datetime.datetime`` instances
  370. - ``decimal.Decimal`` instances
  371. - Any Django field
  372. - Any function or method reference (e.g. ``datetime.datetime.today``)
  373. - Any class reference
  374. - Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`)
  375. Django cannot serialize:
  376. - Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)
  377. - Lambdas
  378. .. _custom-deconstruct-method:
  379. Adding a deconstruct() method
  380. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  381. You can let Django serialize your own custom class instances by giving the class
  382. a ``deconstruct`` method. It takes no arguments, and should return a tuple
  383. of 3 things: ``(path, args, kwargs)``.
  384. ``path`` should be the Python path to the class, with the class name included as the
  385. last part (for example, ``myapp.custom_things.MyClass``). If your class is not
  386. available at the top level of a module it is not serializable.
  387. ``args`` should be a list of positional arguments to pass to your class'
  388. ``__init__`` method. Everything in this list should itself be serializable.
  389. ``kwargs`` should be a dict of keyword arguments to pass to your class'
  390. ``__init__`` method. Every value should itself be serializable.
  391. Django will write out the value as an instantiation of your class with the
  392. given arguments, similar to the way it writes out references to Django fields.
  393. Upgrading from South
  394. --------------------
  395. If you already have pre-existing migrations created with
  396. `South 0.x <http://south.aeracode.org>`_, then the upgrade process to use
  397. ``django.db.migrations`` is quite simple:
  398. * Ensure all installs are fully up-to-date with their migrations
  399. * Delete all your (numbered) migration files, but not the directory or
  400. ``__init__.py`` - make sure you remove the ``.pyc`` files too.
  401. * Run ``python manage.py makemigrations``. Django should see the empty
  402. migration directories and make new initial migrations in the new format.
  403. * Run ``python manage.py migrate``. Django will see that the tables for the
  404. initial migrations already exist and mark them as applied without running
  405. them.
  406. That's it! The only complication is if you have a circular dependency loop
  407. of foreign keys; in this case, ``makemigrations`` might make more than one
  408. initial migration, and you'll need to mark them all as applied using::
  409. python manage.py migrate --fake yourappnamehere