migrations.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 :doc:`SchemaEditor </ref/schema-editor>` 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. cause a full rewrite of the table, for a time proportional to its size.
  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 fully rewrite tables for almost every schema operation
  64. and 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 per
  66. million rows - adding a few columns to a table with just a few million rows
  67. 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 linearize 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. Custom fields
  190. ~~~~~~~~~~~~~
  191. You can't modify the number of positional arguments in an already migrated
  192. custom field without raising a TypeError. The old migration will call the
  193. modified ``__init__`` method with the old signature. So if you need a new
  194. argument, please create a keyword argument and use e.g.
  195. ``assert kwargs.get('argument_name') is not None`` in the constructor.
  196. Adding migrations to apps
  197. -------------------------
  198. Adding migrations to new apps is straightforward - they come preconfigured to
  199. accept migrations, and so just run :djadmin:`makemigrations` once you've made
  200. some changes.
  201. If your app already has models and database tables, and doesn't have migrations
  202. yet (for example, you created it against a previous Django version), you'll
  203. need to convert it to use migrations; this is a simple process::
  204. $ python manage.py makemigrations your_app_label
  205. This will make a new initial migration for your app. Now, when you run
  206. :djadmin:`migrate`, Django will detect that you have an initial migration
  207. *and* that the tables it wants to create already exist, and will mark the
  208. migration as already applied.
  209. Note that this only works given two things:
  210. * You have not changed your models since you made their tables. For migrations
  211. to work, you must make the initial migration *first* and then make changes,
  212. as Django compares changes against migration files, not the database.
  213. * You have not manually edited your database - Django won't be able to detect
  214. that your database doesn't match your models, you'll just get errors when
  215. migrations try to modify those tables.
  216. .. _historical-models:
  217. Historical models
  218. -----------------
  219. When you run migrations, Django is working from historical versions of
  220. your models stored in the migration files. If you write Python code
  221. using the ``django.db.migrations.RunPython`` operation, or if you have
  222. ``allow_migrate`` methods on your database routers, you will be exposed
  223. to these versions of your models.
  224. Because it's impossible to serialize arbitrary Python code, these historical
  225. models will not have any custom methods or managers that you have defined.
  226. They will, however, have the same fields, relationships and ``Meta`` options
  227. (also versioned, so they may be different from your current ones).
  228. .. warning::
  229. This means that you will NOT have custom save() methods called on objects
  230. when you access them in migrations, and you will NOT have any custom constructors
  231. or instance methods. Plan appropriately!
  232. In addition, the base classes of the model are just stored as pointers,
  233. so you must always keep base classes around for as long as there is a migration
  234. that contains a reference to them. On the plus side, methods and managers
  235. from these base classes inherit normally, so if you absolutely need access
  236. to these you can opt to move them into a superclass.
  237. .. _data-migrations:
  238. Data Migrations
  239. ---------------
  240. As well as changing the database schema, you can also use migrations to change
  241. the data in the database itself, in conjunction with the schema if you want.
  242. Migrations that alter data are usually called "data migrations"; they're best
  243. written as separate migrations, sitting alongside your schema migrations.
  244. Django can't automatically generate data migrations for you, as it does with
  245. schema migrations, but it's not very hard to write them. Migration files in
  246. Django are made up of :doc:`Operations </ref/migration-operations>`, and
  247. the main operation you use for data migrations is
  248. :ref:`RunPython <operation-run-python>`.
  249. To start, make an empty migration file you can work from (Django will put
  250. the file in the right place, suggest a name, and add dependencies for you)::
  251. python manage.py makemigrations --empty yourappname
  252. Then, open up the file; it should look something like this::
  253. # encoding: utf8
  254. from django.db import models, migrations
  255. class Migration(migrations.Migration):
  256. dependencies = [
  257. ('yourappname', '0001_initial'),
  258. ]
  259. operations = [
  260. ]
  261. Now, all you need to do is create a new function and have RunPython use it.
  262. RunPython expects a callable as its argument which takes two arguments - the
  263. first is an :doc:`app registry </ref/applications/>` that has the historical
  264. versions of all your models loaded into it to match where in your history the
  265. migration sits, and the second is a :doc:`SchemaEditor </ref/schema-editor>`,
  266. which you can use to manually effect database schema changes (but beware,
  267. doing this can confuse the migration autodetector!)
  268. Let's write a simple migration that populates our new ``name`` field with the
  269. combined values of ``first_name`` and ``last_name`` (we've come to our senses
  270. and realised that not everyone has first and last names). All we
  271. need to do is use the historical model and iterate over the rows::
  272. # encoding: utf8
  273. from django.db import models, migrations
  274. def combine_names(apps, schema_editor):
  275. # We can't import the Person model directly as it may be a newer
  276. # version than this migration expects. We use the historical version.
  277. Person = apps.get_model("yourappname", "Person")
  278. for person in Person.objects.all():
  279. person.name = "%s %s" % (person.first_name, person.last_name)
  280. person.save()
  281. class Migration(migrations.Migration):
  282. dependencies = [
  283. ('yourappname', '0001_initial'),
  284. ]
  285. operations = [
  286. migrations.RunPython(combine_names),
  287. ]
  288. Once that's done, we can just run ``python manage.py migrate`` as normal and
  289. the data migration will run in place alongside other migrations.
  290. If you're interested in the more advanced migration operations, or want
  291. to be able to write your own, see our
  292. :doc:`migration operations reference </ref/migration-operations>`.
  293. .. _migration-serializing:
  294. Serializing values
  295. ------------------
  296. Migrations are just Python files containing the old definitions of your models
  297. - thus, to write them, Django must take the current state of your models and
  298. serialize them out into a file.
  299. While Django can serialize most things, there are some things that we just
  300. can't serialize out into a valid Python representation - there's no Python
  301. standard for how a value can be turned back into code (``repr()`` only works
  302. for basic values, and doesn't specify import paths).
  303. Django can serialize the following:
  304. - ``int``, ``long``, ``float``, ``bool``, ``str``, ``unicode``, ``bytes``, ``None``
  305. - ``list``, ``set``, ``tuple``, ``dict``
  306. - ``datetime.date`` and ``datetime.datetime`` instances
  307. - ``decimal.Decimal`` instances
  308. - Any Django field
  309. - Any function or method reference (e.g. ``datetime.datetime.today``)
  310. - Any class reference
  311. - Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`)
  312. Django cannot serialize:
  313. - Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)
  314. - Lambdas
  315. .. _custom-deconstruct-method:
  316. Adding a deconstruct() method
  317. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  318. You can let Django serialize your own custom class instances by giving the class
  319. a ``deconstruct`` method. It takes no arguments, and should return a tuple
  320. of 3 things: ``(path, args, kwargs)``.
  321. ``path`` should be the Python path to the class, with the class name included as the
  322. last part (for example, ``myapp.custom_things.MyClass``). If your class is not
  323. available at the top level of a module it is not serializable.
  324. ``args`` should be a list of positional arguments to pass to your class'
  325. ``__init__`` method. Everything in this list should itself be serializable.
  326. ``kwargs`` should be a dict of keyword arguments to pass to your class'
  327. ``__init__`` method. Every value should itself be serializable.
  328. Django will write out the value as an instatiation of your class with the
  329. given arguments, similar to the way it writes out references to Django fields.
  330. Upgrading from South
  331. --------------------
  332. If you already have pre-existing migrations created with
  333. `South 0.x <http://south.aeracode.org>`_, then the upgrade process to use
  334. ``django.db.migrations`` is quite simple:
  335. * Ensure all installs are fully up-to-date with their migrations
  336. * Delete all your (numbered) migration files, but not the directory or __init__.py - make sure you remove the ``.pyc`` files too.
  337. * Run ``python manage.py makemigrations``. Django should see the empty migration directories and make new initial migrations in the new format.
  338. * Run ``python manage.py migrate``. Django will see that the tables for the initial migrations already exist and mark them as applied without running them.
  339. That's it! The only complication is if you have a circular dependency loop
  340. of foreign keys; in this case, ``makemigrations`` might make more than one
  341. initial migration, and you'll need to mark them all as applied using::
  342. python manage.py migrate --fake yourappnamehere