migrations.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 ``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 behaviour 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 - analagous 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. Migrations will run the same way every time and produce consistent results,
  41. meaning that what you see in development and staging is exactly what will
  42. happen in production - no unexpected surprises.
  43. Backend Support
  44. ---------------
  45. Migrations are supported on all backends that Django ships with, as well
  46. as any third-party backends if they have programmed in support for schema
  47. alteration (done via the SchemaEditor class).
  48. However, some databases are more capable than others when it comes to
  49. schema migrations; some of the caveats are covered below.
  50. PostgreSQL
  51. ~~~~~~~~~~
  52. PostgreSQL is the most capable of all the databases here in terms of schema
  53. support; the only caveat is that adding columns with default values will
  54. lock a table for a time proportional to the number of rows in it.
  55. For this reason, it's recommended you always create new columns with
  56. ``null=True``, as this way they will be added immediately.
  57. MySQL
  58. ~~~~~
  59. MySQL lacks support for transactions around schema alteration operations,
  60. meaning that if a migration fails to apply you will have to manually unpick
  61. the changes in order to try again (it's impossible to roll back to an
  62. earlier point).
  63. In addition, MySQL will lock tables for almost every schema operation and
  64. generally takes a time proportional to the number of rows in the table to
  65. add or remove columns. On slower hardware this can be worse than a minute
  66. per million rows - adding a few columns to a table with just a few million
  67. rows could lock your site up for over ten minutes.
  68. Finally, MySQL has reasonably small limits on name lengths for columns, tables
  69. and indexes, as well as a limit on the combined size of all columns an index
  70. covers. This means that indexes that are possible on other backends will
  71. fail to be created under MySQL.
  72. SQLite
  73. ~~~~~~
  74. SQLite has very little built-in schema alteration support, and so Django
  75. attempts to emulate it by:
  76. * Creating a new table with the new schema
  77. * Copying the data across
  78. * Dropping the old table
  79. * Renaming the new table to match the original name
  80. This process generally works well, but it can be slow and occasionally
  81. buggy. It is not recommended that you run and migrate SQLite in a
  82. production environment unless you are very aware of the risks and
  83. its limitations; the support Django ships with is designed to allow
  84. developers to use SQLite on their local machines to develop less complex
  85. Django projects without the need for a full database.
  86. Workflow
  87. --------
  88. Working with migrations is simple. Make changes to your models - say, add
  89. a field and remove a model - and then run :djadmin:`makemigrations`::
  90. $ python manage.py makemigrations
  91. Migrations for 'books':
  92. 0003_auto.py:
  93. - Alter field author on book
  94. Your models will be scanned and compared to the versions currently
  95. contained in your migration files, and then a new set of migrations
  96. will be written out. Make sure to read the output to see what
  97. ``makemigrations`` thinks you have changed - it's not perfect, and for
  98. complex changes it might not be detecting what you expect.
  99. Once you have your new migration files, you should apply them to your
  100. database to make sure they work as expected::
  101. $ python manage.py migrate
  102. Operations to perform:
  103. Synchronize unmigrated apps: sessions, admin, messages, auth, staticfiles, contenttypes
  104. Apply all migrations: books
  105. Synchronizing apps without migrations:
  106. Creating tables...
  107. Installing custom SQL...
  108. Installing indexes...
  109. Installed 0 object(s) from 0 fixture(s)
  110. Running migrations:
  111. Applying books.0003_auto... OK
  112. The command runs in two stages; first, it synchronizes unmigrated apps
  113. (performing the same functionality that ``syncdb`` used to provide), and
  114. then it runs any migrations that have not yet been applied.
  115. Once the migration is applied, commit the migration and the models change
  116. to your version control system as a single commit - that way, when other
  117. developers (or your production servers) check out the code, they'll
  118. get both the changes to your models and the accompanying migration at the
  119. same time.
  120. Version control
  121. ~~~~~~~~~~~~~~~
  122. Because migrations are stored in version control, you'll occasionally
  123. come across situations where you and another developer have both committed
  124. a migration to the same app at the same time, resulting in two migrations
  125. with the same number.
  126. Don't worry - the numbers are just there for developers' reference, Django
  127. just cares that each migration has a different name. Migrations specify which
  128. other migrations they depend on - including earlier migrations in the same
  129. app - in the file, so it's possible to detect when there's two new migrations
  130. for the same app that aren't ordered.
  131. When this happens, Django will prompt you and give you some options. If it
  132. thinks it's safe enough, it will offer to automatically linearise the two
  133. migrations for you. If not, you'll have to go in and modify the migrations
  134. yourself - don't worry, this isn't difficult, and is explained more in
  135. :ref:`migration-files` below.
  136. Dependencies
  137. ------------
  138. While migrations are per-app, the tables and relationships implied by
  139. your models are too complex to be created for just one app at a time. When
  140. you make a migration that requires something else to run - for example,
  141. you add a ForeignKey in your ``books`` app to your ``authors`` app - the
  142. resulting migration will contain a dependency on a migration in ``authors``.
  143. This means that when you run the migrations, the ``authors`` migration runs
  144. first and creates the table the ForeignKey references, and then the migration
  145. that makes the ForeignKey column runs afterwards and creates the constraint.
  146. If this didn't happen, the migration would try to create the ForeignKey column
  147. without the table it's referencing existing and your database would
  148. throw an error.
  149. This dependency behaviour affects most migration operations where you
  150. restrict to a single app. Restricting to a single app (either in
  151. ``makemigrations`` or ``migrate``) is a best-efforts promise, and not
  152. a guarantee; any other apps that need to be used to get dependencies correct
  153. will be.
  154. .. migration-files:
  155. Migration files
  156. ---------------
  157. Migrations are stored as an on-disk format, referred to here as
  158. "migration files". These files are actually just normal Python files with
  159. an agreed-upon object layout, written in a declarative style.
  160. A basic migration file looks like this::
  161. from django.db import migrations, models
  162. class Migration(migrations.Migration):
  163. dependencies = [("migrations", "0001_initial")]
  164. operations = [
  165. migrations.DeleteModel("Tribble"),
  166. migrations.AddField("Author", "rating", models.IntegerField(default=0)),
  167. ]
  168. What Django looks for when it loads a migration file (as a Python module) is
  169. a subclass of ``django.db.migrations.Migration`` called ``Migration``. It then
  170. inspects this object for four attributes, only two of which are used
  171. most of the time:
  172. * ``dependencies``, a list of migrations this one depends on.
  173. * ``operations``, a list of Operation classes that define what this migration
  174. does.
  175. The operations are the key; they are a set of declarative instructions which
  176. tell Django what schema changes need to be made. Django scans them and
  177. builds an in-memory representation of all of the schema changes to all apps,
  178. and uses this to generate the SQL which makes the schema changes.
  179. That in-memory structure is also used to work out what the differences are
  180. between your models and the current state of your migrations; Django runs
  181. through all the changes, in order, on an in-memory set of models to come
  182. up with the state of your models last time you ran ``makemigrations``. It
  183. then uses these models to compare against the ones in your ``models.py`` files
  184. to work out what you have changed.
  185. You should rarely, if ever, need to edit migration files by hand, but
  186. it's entirely possible to write them manually if you need to. Some of the
  187. more complex operations are not autodetectable and are only available via
  188. a hand-written migration, so don't be scared about editing them if you have to.
  189. Adding migrations to apps
  190. -------------------------
  191. Adding migrations to new apps is straightforward - they come preconfigured to
  192. accept migrations, and so just run :djadmin:`makemigrations` once you've made
  193. some changes.
  194. If your app already has models and database tables, and doesn't have migrations
  195. yet (for example, you created it against a previous Django version), you'll
  196. need to convert it to use migrations; this is a simple process::
  197. python manage.py makemigrations --force yourappname
  198. This will make a new initial migration for your app (the ``--force`` argument
  199. is to override Django's default behaviour, as it thinks your app does not want
  200. migrations). Now, when you run :djadmin:`migrate`, Django will detect that
  201. you have an initial migration *and* that the tables it wants to create already
  202. exist, and will mark the migration as already applied.
  203. Note that this only works given two things:
  204. * You have not changed your models since you made their tables. For migrations
  205. to work, you must make the initial migration *first* and then make changes,
  206. as Django compares changes against migration files, not the database.
  207. * You have not manually edited your database - Django won't be able to detect
  208. that your database doesn't match your models, you'll just get errors when
  209. migrations try and modify those tables.
  210. .. historical-models:
  211. Historical models
  212. -----------------
  213. When you run migrations, Django is working from historical versions of
  214. your models stored in the migration files. If you write Python code
  215. using the ``django.db.migrations.RunPython`` operation, or if you have
  216. ``allow_migrate`` methods on your database routers, you will be exposed
  217. to these versions of your models.
  218. Because it's impossible to serialize arbitrary Python code, these historical
  219. models will not have any custom methods or managers that you have defined.
  220. They will, however, have the same fields, relationships and ``Meta`` options
  221. (also versioned, so they may be different from your current ones).
  222. In addition, the base classes of the model are just stored as pointers,
  223. so you must always keep base classes around for as long as there is a migration
  224. that contains a reference to them. On the plus side, methods and managers
  225. from these base classes inherit normally, so if you absolutely need access
  226. to these you can opt to move them into a superclass.