migration-operations.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. ====================
  2. Migration Operations
  3. ====================
  4. .. module:: django.db.migrations.operations
  5. Migration files are composed of one or more ``Operation``\s, objects that
  6. declaratively record what the migration should do to your database.
  7. Django also uses these ``Operation`` objects to work out what your models
  8. looked like historically, and to calculate what changes you've made to
  9. your models since the last migration so it can automatically write
  10. your migrations; that's why they're declarative, as it means Django can
  11. easily load them all into memory and run through them without touching
  12. the database to work out what your project should look like.
  13. There are also more specialized ``Operation`` objects which are for things like
  14. :ref:`data migrations <data-migrations>` and for advanced manual database
  15. manipulation. You can also write your own ``Operation`` classes if you want
  16. to encapsulate a custom change you commonly make.
  17. If you need an empty migration file to write your own ``Operation`` objects
  18. into, just use ``python manage.py makemigrations --empty yourappname``,
  19. but be aware that manually adding schema-altering operations can confuse the
  20. migration autodetector and make resulting runs of :djadmin:`makemigrations`
  21. output incorrect code.
  22. All of the core Django operations are available from the
  23. ``django.db.migrations.operations`` module.
  24. For introductory material, see the :doc:`migrations topic guide
  25. </topics/migrations>`.
  26. Schema Operations
  27. =================
  28. CreateModel
  29. -----------
  30. .. class:: CreateModel(name, fields, options=None, bases=None)
  31. Creates a new model in the project history and a corresponding table in the
  32. database to match it.
  33. ``name`` is the model name, as would be written in the ``models.py`` file.
  34. ``fields`` is a list of 2-tuples of ``(field_name, field_instance)``.
  35. The field instance should be an unbound field (so just ``models.CharField()``,
  36. rather than a field takes from another model).
  37. ``options`` is an optional dictionary of values from the model's ``Meta`` class.
  38. ``bases`` is an optional list of other classes to have this model inherit from;
  39. it can contain both class objects as well as strings in the format
  40. ``"appname.ModelName"`` if you want to depend on another model (so you inherit
  41. from the historical version). If it's not supplied, it defaults to just
  42. inheriting from the standard ``models.Model``.
  43. DeleteModel
  44. -----------
  45. .. class:: DeleteModel(name)
  46. Deletes the model from the project history and its table from the database.
  47. RenameModel
  48. -----------
  49. .. class:: RenameModel(old_name, new_name)
  50. Renames the model from an old name to a new one.
  51. You may have to manually add
  52. this if you change the model's name and quite a few of its fields at once; to
  53. the autodetector, this will look like you deleted a model with the old name
  54. and added a new one with a different name, and the migration it creates will
  55. lose any data in the old table.
  56. AlterModelTable
  57. ---------------
  58. .. class:: AlterModelTable(name, table)
  59. Changes the model's table name (the :attr:`~django.db.models.Options.db_table`
  60. option on the ``Meta`` subclass).
  61. AlterUniqueTogether
  62. -------------------
  63. .. class:: AlterUniqueTogether(name, unique_together)
  64. Changes the model's set of unique constraints (the
  65. :attr:`~django.db.models.Options.unique_together` option on the ``Meta``
  66. subclass).
  67. AlterIndexTogether
  68. ------------------
  69. .. class:: AlterIndexTogether(name, index_together)
  70. Changes the model's set of custom indexes (the
  71. :attr:`~django.db.models.Options.index_together` option on the ``Meta``
  72. subclass).
  73. AlterOrderWithRespectTo
  74. -----------------------
  75. .. class:: AlterOrderWithRespectTo(name, order_with_respect_to)
  76. Makes or deletes the ``_order`` column needed for the
  77. :attr:`~django.db.models.Options.order_with_respect_to` option on the ``Meta``
  78. subclass.
  79. AlterModelOptions
  80. -----------------
  81. .. class:: AlterModelOptions(name, options)
  82. Stores changes to miscellaneous model options (settings on a model's ``Meta``)
  83. like ``permissions`` and ``verbose_name``. Does not affect the database, but
  84. persists these changes for :class:`RunPython` instances to use. ``options``
  85. should be a dictionary mapping option names to values.
  86. AddField
  87. --------
  88. .. class:: AddField(model_name, name, field, preserve_default=True)
  89. Adds a field to a model. ``model_name`` is the model's name, ``name`` is
  90. the field's name, and ``field`` is an unbound Field instance (the thing
  91. you would put in the field declaration in ``models.py`` - for example,
  92. ``models.IntegerField(null=True)``.
  93. The ``preserve_default`` argument indicates whether the field's default
  94. value is permanent and should be baked into the project state (``True``),
  95. or if it is temporary and just for this migration (``False``) - usually
  96. because the migration is adding a non-nullable field to a table and needs
  97. a default value to put into existing rows. It does not effect the behavior
  98. of setting defaults in the database directly - Django never sets database
  99. defaults, and always applies them in the Django ORM code.
  100. RemoveField
  101. -----------
  102. .. class:: RemoveField(model_name, name)
  103. Removes a field from a model.
  104. Bear in mind that when reversed this is actually adding a field to a model;
  105. if the field is not nullable this may make this operation irreversible (apart
  106. from any data loss, which of course is irreversible).
  107. AlterField
  108. ----------
  109. .. class:: AlterField(model_name, name, field)
  110. Alters a field's definition, including changes to its type,
  111. :attr:`~django.db.models.Field.null`, :attr:`~django.db.models.Field.unique`,
  112. :attr:`~django.db.models.Field.db_column` and other field attributes.
  113. Note that not all changes are possible on all databases - for example, you
  114. cannot change a text-type field like ``models.TextField()`` into a number-type
  115. field like ``models.IntegerField()`` on most databases.
  116. RenameField
  117. -----------
  118. .. class:: RenameField(model_name, old_name, new_name)
  119. Changes a field's name (and, unless :attr:`~django.db.models.Field.db_column`
  120. is set, its column name).
  121. Special Operations
  122. ==================
  123. RunSQL
  124. ------
  125. .. class:: RunSQL(sql, reverse_sql=None, state_operations=None)
  126. Allows running of arbitrary SQL on the database - useful for more advanced
  127. features of database backends that Django doesn't support directly, like
  128. partial indexes.
  129. ``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on
  130. the database. On most database backends (all but PostgreSQL), Django will
  131. split the SQL into individual statements prior to executing them. This
  132. requires installing the sqlparse_ Python library.
  133. The ``state_operations`` argument is so you can supply operations that are
  134. equivalent to the SQL in terms of project state; for example, if you are
  135. manually creating a column, you should pass in a list containing an ``AddField``
  136. operation here so that the autodetector still has an up-to-date state of the
  137. model (otherwise, when you next run ``makemigrations``, it won't see any
  138. operation that adds that field and so will try to run it again).
  139. .. versionchanged:: 1.7.1
  140. If you want to include literal percent signs in the query you don't need to
  141. double them anymore.
  142. .. _sqlparse: https://pypi.python.org/pypi/sqlparse
  143. RunPython
  144. ---------
  145. .. class:: RunPython(code, reverse_code=None, atomic=True)
  146. Runs custom Python code in a historical context. ``code`` (and ``reverse_code``
  147. if supplied) should be callable objects that accept two arguments; the first is
  148. an instance of ``django.apps.registry.Apps`` containing historical models that
  149. match the operation's place in the project history, and the second is an
  150. instance of :class:`SchemaEditor
  151. <django.db.backends.schema.BaseDatabaseSchemaEditor>`.
  152. You are advised to write the code as a separate function above the ``Migration``
  153. class in the migration file, and just pass it to ``RunPython``. Here's an
  154. example of using ``RunPython`` to create some initial objects on a ``Country``
  155. model::
  156. # -*- coding: utf-8 -*-
  157. from django.db import models, migrations
  158. def forwards_func(apps, schema_editor):
  159. # We get the model from the versioned app registry;
  160. # if we directly import it, it'll be the wrong version
  161. Country = apps.get_model("myapp", "Country")
  162. db_alias = schema_editor.connection.alias
  163. Country.objects.using(db_alias).bulk_create([
  164. Country(name="USA", code="us"),
  165. Country(name="France", code="fr"),
  166. ])
  167. class Migration(migrations.Migration):
  168. dependencies = []
  169. operations = [
  170. migrations.RunPython(
  171. forwards_func,
  172. ),
  173. ]
  174. This is generally the operation you would use to create
  175. :ref:`data migrations <data-migrations>`, run
  176. custom data updates and alterations, and anything else you need access to an
  177. ORM and/or python code for.
  178. If you're upgrading from South, this is basically the South pattern as an
  179. operation - one or two methods for forwards and backwards, with an ORM and
  180. schema operations available. Most of the time, you should be able to translate
  181. the ``orm.Model`` or ``orm["appname", "Model"]`` references from South directly
  182. into ``apps.get_model("appname", "Model")`` references here and leave most of
  183. the rest of the code unchanged for data migrations. However, ``apps`` will only
  184. have references to models in the current app unless migrations in other apps
  185. are added to the migration's dependencies.
  186. Much like :class:`RunSQL`, ensure that if you change schema inside here you're
  187. either doing it outside the scope of the Django model system (e.g. triggers)
  188. or that you use :class:`SeparateDatabaseAndState` to add in operations that will
  189. reflect your changes to the model state - otherwise, the versioned ORM and
  190. the autodetector will stop working correctly.
  191. By default, ``RunPython`` will run its contents inside a transaction even
  192. on databases that do not support DDL transactions (for example, MySQL and
  193. Oracle). This should be safe, but may cause a crash if you attempt to use
  194. the ``schema_editor`` provided on these backends; in this case, please
  195. set ``atomic=False``.
  196. .. warning::
  197. ``RunPython`` does not magically alter the connection of the models for you;
  198. any model methods you call will go to the default database unless you
  199. give them the current database alias (available from
  200. ``schema_editor.connection.alias``, where ``schema_editor`` is the second
  201. argument to your function).
  202. SeparateDatabaseAndState
  203. ------------------------
  204. .. class:: SeparateDatabaseAndState(database_operations=None, state_operations=None)
  205. A highly specialized operation that let you mix and match the database
  206. (schema-changing) and state (autodetector-powering) aspects of operations.
  207. It accepts two list of operations, and when asked to apply state will use the
  208. state list, and when asked to apply changes to the database will use the database
  209. list. Do not use this operation unless you're very sure you know what you're doing.
  210. Writing your own
  211. ================
  212. Operations have a relatively simple API, and they're designed so that you can
  213. easily write your own to supplement the built-in Django ones. The basic structure
  214. of an ``Operation`` looks like this::
  215. from django.db.migrations.operations.base import Operation
  216. class MyCustomOperation(Operation):
  217. # If this is False, it means that this operation will be ignored by
  218. # sqlmigrate; if true, it will be run and the SQL collected for its output.
  219. reduces_to_sql = False
  220. # If this is False, Django will refuse to reverse past this operation.
  221. reversible = False
  222. def __init__(self, arg1, arg2):
  223. # Operations are usually instantiated with arguments in migration
  224. # files. Store the values of them on self for later use.
  225. pass
  226. def state_forwards(self, app_label, state):
  227. # The Operation should take the 'state' parameter (an instance of
  228. # django.db.migrations.state.ProjectState) and mutate it to match
  229. # any schema changes that have occurred.
  230. pass
  231. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  232. # The Operation should use schema_editor to apply any changes it
  233. # wants to make to the database.
  234. pass
  235. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  236. # If reversible is True, this is called when the operation is reversed.
  237. pass
  238. def describe(self):
  239. # This is used to describe what the operation does in console output.
  240. return "Custom Operation"
  241. You can take this template and work from it, though we suggest looking at the
  242. built-in Django operations in ``django.db.migrations.operations`` - they're
  243. easy to read and cover a lot of the example usage of semi-internal aspects
  244. of the migration framework like ``ProjectState`` and the patterns used to get
  245. historical models.
  246. Some things to note:
  247. * You don't need to learn too much about ``ProjectState`` to just write simple
  248. migrations; just know that it has a ``.render()`` method that turns it into
  249. an app registry (which you can then call ``get_model`` on).
  250. * ``database_forwards`` and ``database_backwards`` both get two states passed
  251. to them; these just represent the difference the ``state_forwards`` method
  252. would have applied, but are given to you for convenience and speed reasons.
  253. * ``to_state`` in the database_backwards method is the *older* state; that is,
  254. the one that will be the current state once the migration has finished reversing.
  255. * You might see implementations of ``references_model`` on the built-in
  256. operations; this is part of the autodetection code and does not matter for
  257. custom operations.
  258. As a simple example, let's make an operation that loads PostgreSQL extensions
  259. (which contain some of PostgreSQL's more exciting features). It's simple enough;
  260. there's no model state changes, and all it does is run one command::
  261. from django.db.migrations.operations.base import Operation
  262. class LoadExtension(Operation):
  263. reversible = True
  264. def __init__(self, name):
  265. self.name = name
  266. def state_forwards(self, app_label, state):
  267. pass
  268. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  269. schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
  270. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  271. schema_editor.execute("DROP EXTENSION %s" % self.name)
  272. def describe(self):
  273. return "Creates extension %s" % self.name