migration-operations.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. ====================
  2. Migration Operations
  3. ====================
  4. Migration files are composed of one or more Operations, objects that
  5. declaratively record what the migration should do to your database.
  6. Django also uses these Operation objects to work out what your models
  7. looked like historically, and to calculate what changes you've made to
  8. your models since the last migration so it can automatically write
  9. your migrations; that's why they're declarative, as it means Django can
  10. easily load them all into memory and run through them without touching
  11. the database to work out what your project should look like.
  12. There are also more specialised Operation objects which are for things like
  13. :ref:`data migrations <data-migrations>` and for advanced manual database
  14. manipulation. You can also write your own Operation classes if you want
  15. to encapsulate a custom change you commonly make.
  16. If you need an empty migration file to write your own Operation objects
  17. into, just use ``python manage.py makemigrations --empty yourappname``,
  18. but be aware that manually adding schema-altering operations can confuse the
  19. migration autodetector and make resulting runs of ``makemigrations`` output
  20. incorrect code.
  21. All of the core Django operations are available from the
  22. ``django.db.migrations.operations`` module.
  23. Schema Operations
  24. =================
  25. CreateModel
  26. -----------
  27. ::
  28. CreateModel(name, fields, options=None, bases=None)
  29. Creates a new model in the project history and a corresponding table in the
  30. database to match it.
  31. ``name`` is the model name, as would be written in the ``models.py`` file.
  32. ``fields`` is a list of 2-tuples of ``(field_name, field_instance)``.
  33. The field instance should be an unbound field (so just ``models.CharField()``,
  34. rather than a field takes from another model).
  35. ``options`` is an optional dictionary of values from the model's ``Meta`` class.
  36. ``bases`` is an optional list of other classes to have this model inherit from;
  37. it can contain both class objects as well as strings in the format
  38. ``"appname.ModelName"`` if you want to depend on another model (so you inherit
  39. from the historical version). If it's not supplied, it defaults to just
  40. inheriting from the standard ``models.Model``.
  41. DeleteModel
  42. -----------
  43. ::
  44. DeleteModel(name)
  45. Deletes the model from the project history and its table from the database.
  46. RenameModel
  47. -----------
  48. ::
  49. 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. ::
  59. AlterModelTable(name, table)
  60. Changes the model's table name (the ``db_table`` option on the ``Meta`` subclass)
  61. AlterUniqueTogether
  62. -------------------
  63. ::
  64. AlterUniqueTogether(name, unique_together)
  65. Changes the model's set of unique constraints
  66. (the ``unique_together`` option on the ``Meta`` subclass)
  67. AlterIndexTogether
  68. ------------------
  69. ::
  70. AlterIndexTogether(name, index_together)
  71. Changes the model's set of custom indexes
  72. (the ``index_together`` option on the ``Meta`` subclass)
  73. AddField
  74. --------
  75. ::
  76. AddField(model_name, name, field, preserve_default=True)
  77. Adds a field to a model. ``model_name`` is the model's name, ``name`` is
  78. the field's name, and ``field`` is an unbound Field instance (the thing
  79. you would put in the field declaration in ``models.py`` - for example,
  80. ``models.IntegerField(null=True)``.
  81. The ``preserve_default`` argument indicates whether the field's default
  82. value is permanent and should be baked into the project state (``True``),
  83. or if it is temporary and just for this migration (``False``) - usually
  84. because the migration is adding a non-nullable field to a table and needs
  85. a default value to put into existing rows. It does not effect the behavior
  86. of setting defaults in the database directly - Django never sets database
  87. defaults, and always applies them in the Django ORM code.
  88. RemoveField
  89. -----------
  90. ::
  91. RemoveField(model_name, name)
  92. Removes a field from a model.
  93. Bear in mind that when reversed this is actually adding a field to a model;
  94. if the field is not nullable this may make this operation irreversible (apart
  95. from any data loss, which of course is irreversible).
  96. AlterField
  97. ----------
  98. ::
  99. AlterField(model_name, name, field)
  100. Alters a field's definition, including changes to its type, ``null``, ``unique``,
  101. ``db_column`` and other field attributes.
  102. Note that not all changes are possible on all databases - for example, you
  103. cannot change a text-type field like ``models.TextField()`` into a number-type
  104. field like ``models.IntegerField()`` on most databases.
  105. RenameField
  106. -----------
  107. ::
  108. RenameField(model_name, old_name, new_name)
  109. Changes a field's name (and, unless ``db_column`` is set, its column name).
  110. Special Operations
  111. ==================
  112. RunSQL
  113. ------
  114. ::
  115. RunSQL(sql, reverse_sql=None, state_operations=None, multiple=False)
  116. Allows runnning of arbitrary SQL on the database - useful for more advanced
  117. features of database backends that Django doesn't support directly, like
  118. partial indexes.
  119. ``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on the
  120. database. They will be passed to the database as a single SQL statement unless
  121. ``multiple`` is set to ``True``, in which case they will be split into separate
  122. statements manually by the operation before being passed through.
  123. In some extreme cases, the built-in statement splitter may not be able to split
  124. correctly, in which case you should manually split the SQL into multiple calls
  125. to ``RunSQL``.
  126. The ``state_operations`` argument is so you can supply operations that are
  127. equivalent to the SQL in terms of project state; for example, if you are
  128. manually creating a column, you should pass in a list containing an ``AddField``
  129. operation here so that the autodetector still has an up-to-date state of the
  130. model (otherwise, when you next run ``makemigrations``, it won't see any
  131. operation that adds that field and so will try to run it again).
  132. .. _operation-run-python:
  133. RunPython
  134. ---------
  135. ::
  136. RunPython(code, reverse_code=None)
  137. Runs custom Python code in a historical context. ``code`` (and ``reverse_code``
  138. if supplied) should be callable objects that accept two arguments; the first is
  139. an instance of ``django.apps.registry.Apps`` containing historical models that
  140. match the operation's place in the project history, and the second is an
  141. instance of SchemaEditor.
  142. You are advised to write the code as a separate function above the ``Migration``
  143. class in the migration file, and just pass it to ``RunPython``.
  144. SeparateDatabaseAndState
  145. ------------------------
  146. ::
  147. SeparateDatabaseAndState(database_operations=None, state_operations=None)
  148. A highly specalist operation that let you mix and match the database
  149. (schema-changing) and state (autodetector-powering) aspects of operations.
  150. It accepts two list of operations, and when asked to apply state will use the
  151. state list, and when asked to apply changes to the database will use the database
  152. list. Do not use this operation unless you're very sure you know what you're doing.
  153. Writing your own
  154. ================
  155. Operations have a relatively simple API, and they're designed so that you can
  156. easily write your own to supplement the built-in Django ones. The basic structure
  157. of an Operation looks like this::
  158. from django.db.migrations.operations.base import Operation
  159. class MyCustomOperation(Operation):
  160. # If this is False, it means that this operation will be ignored by
  161. # sqlmigrate; if true, it will be run and the SQL collected for its output.
  162. reduces_to_sql = False
  163. # If this is False, Django will refuse to reverse past this operation.
  164. reversible = False
  165. def __init__(self, arg1, arg2):
  166. # Operations are usually instantiated with arguments in migration
  167. # files. Store the values of them on self for later use.
  168. pass
  169. def state_forwards(self, app_label, state):
  170. # The Operation should take the 'state' parameter (an instance of
  171. # django.db.migrations.state.ProjectState) and mutate it to match
  172. # any schema changes that have occurred.
  173. pass
  174. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  175. # The Operation should use schema_editor to apply any changes it
  176. # wants to make to the database.
  177. pass
  178. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  179. # If reversible is True, this is called when the operation is reversed.
  180. pass
  181. def describe(self):
  182. # This is used to describe what the operation does in console output.
  183. return "Custom Operation"
  184. You can take this template and work from it, though we suggest looking at the
  185. built-in Django operations in ``django.db.migrations.operations`` - they're
  186. easy to read and cover a lot of the example usage of semi-internal aspects
  187. of the migration framework like ``ProjectState`` and the patterns used to get
  188. historical models.
  189. Some things to note:
  190. * You don't need to learn too much about ProjectState to just write simple
  191. migrations; just know that it has a ``.render()`` method that turns it into
  192. an app registry (which you can then call ``get_model`` on).
  193. * ``database_forwards`` and ``database_backwards`` both get two states passed
  194. to them; these just represent the difference the ``state_forwards`` method
  195. would have applied, but are given to you for convenience and speed reasons.
  196. * ``to_state`` in the database_backwards method is the *older* state; that is,
  197. the one that will be the current state once the migration has finished reversing.
  198. * You might see implementations of ``references_model`` on the built-in
  199. operations; this is part of the autodetection code and does not matter for
  200. custom operations.
  201. As a simple example, let's make an operation that loads PostgreSQL extensions
  202. (which contain some of PostgreSQL's more exciting features). It's simple enough;
  203. there's no model state changes, and all it does is run one command::
  204. from django.db.migrations.operations.base import Operation
  205. class LoadExtension(Operation):
  206. reversible = True
  207. def __init__(self, name):
  208. self.name = name
  209. def state_forwards(self, app_label, state):
  210. pass
  211. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  212. schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
  213. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  214. schema_editor.execute("DROP EXTENSION %s" % self.name)
  215. def describe(self):
  216. return "Creates extension %s" % self.name