migration-operations.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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, use ``python manage.py makemigrations --empty yourappname``, but be aware
  19. that manually adding schema-altering operations can confuse the migration
  20. autodetector and make resulting runs of :djadmin:`makemigrations` output
  21. 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, managers=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
  36. ``models.CharField(...)``, rather than a field taken 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 inheriting
  42. from the standard ``models.Model``.
  43. ``managers`` takes a list of 2-tuples of ``(manager_name, manager_instance)``.
  44. The first manager in the list will be the default manager for this model during
  45. migrations.
  46. ``DeleteModel``
  47. ---------------
  48. .. class:: DeleteModel(name)
  49. Deletes the model from the project history and its table from the database.
  50. ``RenameModel``
  51. ---------------
  52. .. class:: RenameModel(old_name, new_name)
  53. Renames the model from an old name to a new one.
  54. You may have to manually add
  55. this if you change the model's name and quite a few of its fields at once; to
  56. the autodetector, this will look like you deleted a model with the old name
  57. and added a new one with a different name, and the migration it creates will
  58. lose any data in the old table.
  59. ``AlterModelTable``
  60. -------------------
  61. .. class:: AlterModelTable(name, table)
  62. Changes the model's table name (the :attr:`~django.db.models.Options.db_table`
  63. option on the ``Meta`` subclass).
  64. ``AlterModelTableComment``
  65. --------------------------
  66. .. class:: AlterModelTableComment(name, table_comment)
  67. Changes the model's table comment (the
  68. :attr:`~django.db.models.Options.db_table_comment` option on the ``Meta``
  69. subclass).
  70. ``AlterUniqueTogether``
  71. -----------------------
  72. .. class:: AlterUniqueTogether(name, unique_together)
  73. Changes the model's set of unique constraints (the
  74. :attr:`~django.db.models.Options.unique_together` option on the ``Meta``
  75. subclass).
  76. ``AlterIndexTogether``
  77. ----------------------
  78. .. class:: AlterIndexTogether(name, index_together)
  79. Changes the model's set of custom indexes (the ``index_together`` option on the
  80. ``Meta`` subclass).
  81. .. warning::
  82. ``AlterIndexTogether`` is officially supported only for pre-Django 4.2
  83. migration files. For backward compatibility reasons, it's still part of the
  84. public API, and there's no plan to deprecate or remove it, but it should
  85. not be used for new migrations. Use
  86. :class:`~django.db.migrations.operations.AddIndex` and
  87. :class:`~django.db.migrations.operations.RemoveIndex` operations instead.
  88. ``AlterOrderWithRespectTo``
  89. ---------------------------
  90. .. class:: AlterOrderWithRespectTo(name, order_with_respect_to)
  91. Makes or deletes the ``_order`` column needed for the
  92. :attr:`~django.db.models.Options.order_with_respect_to` option on the ``Meta``
  93. subclass.
  94. ``AlterModelOptions``
  95. ---------------------
  96. .. class:: AlterModelOptions(name, options)
  97. Stores changes to miscellaneous model options (settings on a model's ``Meta``)
  98. like ``permissions`` and ``verbose_name``. Does not affect the database, but
  99. persists these changes for :class:`RunPython` instances to use. ``options``
  100. should be a dictionary mapping option names to values.
  101. ``AlterModelManagers``
  102. ----------------------
  103. .. class:: AlterModelManagers(name, managers)
  104. Alters the managers that are available during migrations.
  105. ``AddField``
  106. ------------
  107. .. class:: AddField(model_name, name, field, preserve_default=True)
  108. Adds a field to a model. ``model_name`` is the model's name, ``name`` is
  109. the field's name, and ``field`` is an unbound Field instance (the thing
  110. you would put in the field declaration in ``models.py`` - for example,
  111. ``models.IntegerField(null=True)``.
  112. The ``preserve_default`` argument indicates whether the field's default
  113. value is permanent and should be baked into the project state (``True``),
  114. or if it is temporary and just for this migration (``False``) - usually
  115. because the migration is adding a non-nullable field to a table and needs
  116. a default value to put into existing rows. It does not affect the behavior
  117. of setting defaults in the database directly - Django never sets database
  118. defaults and always applies them in the Django ORM code.
  119. .. warning::
  120. On older databases, adding a field with a default value may cause a full
  121. rewrite of the table. This happens even for nullable fields and may have a
  122. negative performance impact. To avoid that, the following steps should be
  123. taken.
  124. * Add the nullable field without the default value and run the
  125. :djadmin:`makemigrations` command. This should generate a migration with
  126. an ``AddField`` operation.
  127. * Add the default value to your field and run the :djadmin:`makemigrations`
  128. command. This should generate a migration with an ``AlterField``
  129. operation.
  130. ``RemoveField``
  131. ---------------
  132. .. class:: RemoveField(model_name, name)
  133. Removes a field from a model.
  134. Bear in mind that when reversed, this is actually adding a field to a model.
  135. The operation is reversible (apart from any data loss, which is irreversible)
  136. if the field is nullable or if it has a default value that can be used to
  137. populate the recreated column. If the field is not nullable and does not have a
  138. default value, the operation is irreversible.
  139. .. admonition:: PostgreSQL
  140. ``RemoveField`` will also delete any additional database objects that are
  141. related to the removed field (like views, for example). This is because the
  142. resulting ``DROP COLUMN`` statement will include the ``CASCADE`` clause to
  143. ensure `dependent objects outside the table are also dropped`_.
  144. .. _dependent objects outside the table are also dropped: https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-PARMS-CASCADE
  145. ``AlterField``
  146. --------------
  147. .. class:: AlterField(model_name, name, field, preserve_default=True)
  148. Alters a field's definition, including changes to its type,
  149. :attr:`~django.db.models.Field.null`, :attr:`~django.db.models.Field.unique`,
  150. :attr:`~django.db.models.Field.db_column` and other field attributes.
  151. The ``preserve_default`` argument indicates whether the field's default
  152. value is permanent and should be baked into the project state (``True``),
  153. or if it is temporary and just for this migration (``False``) - usually
  154. because the migration is altering a nullable field to a non-nullable one and
  155. needs a default value to put into existing rows. It does not affect the
  156. behavior of setting defaults in the database directly - Django never sets
  157. database defaults and always applies them in the Django ORM code.
  158. Note that not all changes are possible on all databases - for example, you
  159. cannot change a text-type field like ``models.TextField()`` into a number-type
  160. field like ``models.IntegerField()`` on most databases.
  161. ``RenameField``
  162. ---------------
  163. .. class:: RenameField(model_name, old_name, new_name)
  164. Changes a field's name (and, unless :attr:`~django.db.models.Field.db_column`
  165. is set, its column name).
  166. ``AddIndex``
  167. ------------
  168. .. class:: AddIndex(model_name, index)
  169. Creates an index in the database table for the model with ``model_name``.
  170. ``index`` is an instance of the :class:`~django.db.models.Index` class.
  171. ``RemoveIndex``
  172. ---------------
  173. .. class:: RemoveIndex(model_name, name)
  174. Removes the index named ``name`` from the model with ``model_name``.
  175. ``RenameIndex``
  176. ---------------
  177. .. class:: RenameIndex(model_name, new_name, old_name=None, old_fields=None)
  178. Renames an index in the database table for the model with ``model_name``.
  179. Exactly one of ``old_name`` and ``old_fields`` can be provided. ``old_fields``
  180. is an iterable of the strings, often corresponding to fields of
  181. ``index_together`` (pre-Django 5.1 option).
  182. On databases that don't support an index renaming statement (SQLite and MariaDB
  183. < 10.5.2), the operation will drop and recreate the index, which can be
  184. expensive.
  185. ``AddConstraint``
  186. -----------------
  187. .. class:: AddConstraint(model_name, constraint)
  188. Creates a :doc:`constraint </ref/models/constraints>` in the database table for
  189. the model with ``model_name``.
  190. ``RemoveConstraint``
  191. --------------------
  192. .. class:: RemoveConstraint(model_name, name)
  193. Removes the constraint named ``name`` from the model with ``model_name``.
  194. Special Operations
  195. ==================
  196. ``RunSQL``
  197. ----------
  198. .. class:: RunSQL(sql, reverse_sql=None, state_operations=None, hints=None, elidable=False)
  199. Allows running of arbitrary SQL on the database - useful for more advanced
  200. features of database backends that Django doesn't support directly.
  201. ``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on
  202. the database. On most database backends (all but PostgreSQL), Django will
  203. split the SQL into individual statements prior to executing them.
  204. .. warning::
  205. On PostgreSQL and SQLite, only use ``BEGIN`` or ``COMMIT`` in your SQL in
  206. :ref:`non-atomic migrations <non-atomic-migrations>`, to avoid breaking
  207. Django's transaction state.
  208. You can also pass a list of strings or 2-tuples. The latter is used for passing
  209. queries and parameters in the same way as :ref:`cursor.execute()
  210. <executing-custom-sql>`. These three operations are equivalent::
  211. migrations.RunSQL("INSERT INTO musician (name) VALUES ('Reinhardt');")
  212. migrations.RunSQL([("INSERT INTO musician (name) VALUES ('Reinhardt');", None)])
  213. migrations.RunSQL([("INSERT INTO musician (name) VALUES (%s);", ["Reinhardt"])])
  214. If you want to include literal percent signs in the query, you have to double
  215. them if you are passing parameters.
  216. The ``reverse_sql`` queries are executed when the migration is unapplied. They
  217. should undo what is done by the ``sql`` queries. For example, to undo the above
  218. insertion with a deletion::
  219. migrations.RunSQL(
  220. sql=[("INSERT INTO musician (name) VALUES (%s);", ["Reinhardt"])],
  221. reverse_sql=[("DELETE FROM musician where name=%s;", ["Reinhardt"])],
  222. )
  223. If ``reverse_sql`` is ``None`` (the default), the ``RunSQL`` operation is
  224. irreversible.
  225. The ``state_operations`` argument allows you to supply operations that are
  226. equivalent to the SQL in terms of project state. For example, if you are
  227. manually creating a column, you should pass in a list containing an ``AddField``
  228. operation here so that the autodetector still has an up-to-date state of the
  229. model. If you don't, when you next run ``makemigrations``, it won't see any
  230. operation that adds that field and so will try to run it again. For example::
  231. migrations.RunSQL(
  232. "ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
  233. state_operations=[
  234. migrations.AddField(
  235. "musician",
  236. "name",
  237. models.CharField(max_length=255),
  238. ),
  239. ],
  240. )
  241. The optional ``hints`` argument will be passed as ``**hints`` to the
  242. :meth:`allow_migrate` method of database routers to assist them in making
  243. routing decisions. See :ref:`topics-db-multi-db-hints` for more details on
  244. database hints.
  245. The optional ``elidable`` argument determines whether or not the operation will
  246. be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
  247. .. attribute:: RunSQL.noop
  248. Pass the ``RunSQL.noop`` attribute to ``sql`` or ``reverse_sql`` when you
  249. want the operation not to do anything in the given direction. This is
  250. especially useful in making the operation reversible.
  251. ``RunPython``
  252. -------------
  253. .. class:: RunPython(code, reverse_code=None, atomic=None, hints=None, elidable=False)
  254. Runs custom Python code in a historical context. ``code`` (and ``reverse_code``
  255. if supplied) should be callable objects that accept two arguments; the first is
  256. an instance of ``django.apps.registry.Apps`` containing historical models that
  257. match the operation's place in the project history, and the second is an
  258. instance of :class:`SchemaEditor
  259. <django.db.backends.base.schema.BaseDatabaseSchemaEditor>`.
  260. The ``reverse_code`` argument is called when unapplying migrations. This
  261. callable should undo what is done in the ``code`` callable so that the
  262. migration is reversible. If ``reverse_code`` is ``None`` (the default), the
  263. ``RunPython`` operation is irreversible.
  264. The optional ``hints`` argument will be passed as ``**hints`` to the
  265. :meth:`allow_migrate` method of database routers to assist them in making a
  266. routing decision. See :ref:`topics-db-multi-db-hints` for more details on
  267. database hints.
  268. The optional ``elidable`` argument determines whether or not the operation will
  269. be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
  270. You are advised to write the code as a separate function above the ``Migration``
  271. class in the migration file, and pass it to ``RunPython``. Here's an example of
  272. using ``RunPython`` to create some initial objects on a ``Country`` model::
  273. from django.db import migrations
  274. def forwards_func(apps, schema_editor):
  275. # We get the model from the versioned app registry;
  276. # if we directly import it, it'll be the wrong version
  277. Country = apps.get_model("myapp", "Country")
  278. db_alias = schema_editor.connection.alias
  279. Country.objects.using(db_alias).bulk_create(
  280. [
  281. Country(name="USA", code="us"),
  282. Country(name="France", code="fr"),
  283. ]
  284. )
  285. def reverse_func(apps, schema_editor):
  286. # forwards_func() creates two Country instances,
  287. # so reverse_func() should delete them.
  288. Country = apps.get_model("myapp", "Country")
  289. db_alias = schema_editor.connection.alias
  290. Country.objects.using(db_alias).filter(name="USA", code="us").delete()
  291. Country.objects.using(db_alias).filter(name="France", code="fr").delete()
  292. class Migration(migrations.Migration):
  293. dependencies = []
  294. operations = [
  295. migrations.RunPython(forwards_func, reverse_func),
  296. ]
  297. This is generally the operation you would use to create
  298. :ref:`data migrations <data-migrations>`, run
  299. custom data updates and alterations, and anything else you need access to an
  300. ORM and/or Python code for.
  301. Much like :class:`RunSQL`, ensure that if you change schema inside here you're
  302. either doing it outside the scope of the Django model system (e.g. triggers)
  303. or that you use :class:`SeparateDatabaseAndState` to add in operations that will
  304. reflect your changes to the model state - otherwise, the versioned ORM and
  305. the autodetector will stop working correctly.
  306. By default, ``RunPython`` will run its contents inside a transaction on
  307. databases that do not support DDL transactions (for example, MySQL and
  308. Oracle). This should be safe, but may cause a crash if you attempt to use
  309. the ``schema_editor`` provided on these backends; in this case, pass
  310. ``atomic=False`` to the ``RunPython`` operation.
  311. On databases that do support DDL transactions (SQLite and PostgreSQL),
  312. ``RunPython`` operations do not have any transactions automatically added
  313. besides the transactions created for each migration. Thus, on PostgreSQL, for
  314. example, you should avoid combining schema changes and ``RunPython`` operations
  315. in the same migration or you may hit errors like ``OperationalError: cannot
  316. ALTER TABLE "mytable" because it has pending trigger events``.
  317. If you have a different database and aren't sure if it supports DDL
  318. transactions, check the ``django.db.connection.features.can_rollback_ddl``
  319. attribute.
  320. If the ``RunPython`` operation is part of a :ref:`non-atomic migration
  321. <non-atomic-migrations>`, the operation will only be executed in a transaction
  322. if ``atomic=True`` is passed to the ``RunPython`` operation.
  323. .. warning::
  324. ``RunPython`` does not magically alter the connection of the models for you;
  325. any model methods you call will go to the default database unless you
  326. give them the current database alias (available from
  327. ``schema_editor.connection.alias``, where ``schema_editor`` is the second
  328. argument to your function).
  329. .. staticmethod:: RunPython.noop
  330. Pass the ``RunPython.noop`` method to ``code`` or ``reverse_code`` when
  331. you want the operation not to do anything in the given direction. This is
  332. especially useful in making the operation reversible.
  333. ``SeparateDatabaseAndState``
  334. ----------------------------
  335. .. class:: SeparateDatabaseAndState(database_operations=None, state_operations=None)
  336. A highly specialized operation that lets you mix and match the database
  337. (schema-changing) and state (autodetector-powering) aspects of operations.
  338. It accepts two lists of operations. When asked to apply state, it will use the
  339. ``state_operations`` list (this is a generalized version of :class:`RunSQL`'s
  340. ``state_operations`` argument). When asked to apply changes to the database, it
  341. will use the ``database_operations`` list.
  342. If the actual state of the database and Django's view of the state get out of
  343. sync, this can break the migration framework, even leading to data loss. It's
  344. worth exercising caution and checking your database and state operations
  345. carefully. You can use :djadmin:`sqlmigrate` and :djadmin:`dbshell` to check
  346. your database operations. You can use :djadmin:`makemigrations`, especially
  347. with :option:`--dry-run<makemigrations --dry-run>`, to check your state
  348. operations.
  349. For an example using ``SeparateDatabaseAndState``, see
  350. :ref:`changing-a-manytomanyfield-to-use-a-through-model`.
  351. Operation category
  352. ==================
  353. .. versionadded:: 5.1
  354. .. currentmodule:: django.db.migrations.operations.base
  355. .. class:: OperationCategory
  356. Categories of migration operation used by the :djadmin:`makemigrations`
  357. command to display meaningful symbols.
  358. .. attribute:: ADDITION
  359. *Symbol*: ``+``
  360. .. attribute:: REMOVAL
  361. *Symbol*: ``-``
  362. .. attribute:: ALTERATION
  363. *Symbol*: ``~``
  364. .. attribute:: PYTHON
  365. *Symbol*: ``p``
  366. .. attribute:: SQL
  367. *Symbol*: ``s``
  368. .. attribute:: MIXED
  369. *Symbol*: ``?``
  370. .. _writing-your-own-migration-operation:
  371. Writing your own
  372. ================
  373. Operations have a relatively simple API, and they're designed so that you can
  374. easily write your own to supplement the built-in Django ones. The basic
  375. structure of an ``Operation`` looks like this::
  376. from django.db.migrations.operations.base import Operation
  377. class MyCustomOperation(Operation):
  378. # If this is False, it means that this operation will be ignored by
  379. # sqlmigrate; if true, it will be run and the SQL collected for its output.
  380. reduces_to_sql = False
  381. # If this is False, Django will refuse to reverse past this operation.
  382. reversible = False
  383. # This categorizes the operation. The corresponding symbol will be
  384. # displayed by the makemigrations command.
  385. category = OperationCategory.ADDITION
  386. def __init__(self, arg1, arg2):
  387. # Operations are usually instantiated with arguments in migration
  388. # files. Store the values of them on self for later use.
  389. pass
  390. def state_forwards(self, app_label, state):
  391. # The Operation should take the 'state' parameter (an instance of
  392. # django.db.migrations.state.ProjectState) and mutate it to match
  393. # any schema changes that have occurred.
  394. pass
  395. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  396. # The Operation should use schema_editor to apply any changes it
  397. # wants to make to the database.
  398. pass
  399. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  400. # If reversible is True, this is called when the operation is reversed.
  401. pass
  402. def describe(self):
  403. # This is used to describe what the operation does.
  404. return "Custom Operation"
  405. @property
  406. def migration_name_fragment(self):
  407. # Optional. A filename part suitable for automatically naming a
  408. # migration containing this operation, or None if not applicable.
  409. return "custom_operation_%s_%s" % (self.arg1, self.arg2)
  410. You can take this template and work from it, though we suggest looking at the
  411. built-in Django operations in ``django.db.migrations.operations`` - they cover
  412. a lot of the example usage of semi-internal aspects of the migration framework
  413. like ``ProjectState`` and the patterns used to get historical models, as well
  414. as ``ModelState`` and the patterns used to mutate historical models in
  415. ``state_forwards()``.
  416. Some things to note:
  417. * You don't need to learn too much about ``ProjectState`` to write migrations;
  418. just know that it has an ``apps`` property that gives access to an app
  419. registry (which you can then call ``get_model`` on).
  420. * ``database_forwards`` and ``database_backwards`` both get two states passed
  421. to them; these represent the difference the ``state_forwards`` method would
  422. have applied, but are given to you for convenience and speed reasons.
  423. * If you want to work with model classes or model instances from the
  424. ``from_state`` argument in ``database_forwards()`` or
  425. ``database_backwards()``, you must render model states using the
  426. ``clear_delayed_apps_cache()`` method to make related models available::
  427. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  428. # This operation should have access to all models. Ensure that all models are
  429. # reloaded in case any are delayed.
  430. from_state.clear_delayed_apps_cache()
  431. ...
  432. * ``to_state`` in the database_backwards method is the *older* state; that is,
  433. the one that will be the current state once the migration has finished reversing.
  434. * You might see implementations of ``references_model`` on the built-in
  435. operations; this is part of the autodetection code and does not matter for
  436. custom operations.
  437. .. warning::
  438. For performance reasons, the :class:`~django.db.models.Field` instances in
  439. ``ModelState.fields`` are reused across migrations. You must never change
  440. the attributes on these instances. If you need to mutate a field in
  441. ``state_forwards()``, you must remove the old instance from
  442. ``ModelState.fields`` and add a new instance in its place. The same is true
  443. for the :class:`~django.db.models.Manager` instances in
  444. ``ModelState.managers``.
  445. As an example, let's make an operation that loads PostgreSQL extensions (which
  446. contain some of PostgreSQL's more exciting features). Since there's no model
  447. state changes, all it does is run one command::
  448. from django.db.migrations.operations.base import Operation
  449. class LoadExtension(Operation):
  450. reversible = True
  451. def __init__(self, name):
  452. self.name = name
  453. def state_forwards(self, app_label, state):
  454. pass
  455. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  456. schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
  457. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  458. schema_editor.execute("DROP EXTENSION %s" % self.name)
  459. def describe(self):
  460. return "Creates extension %s" % self.name
  461. @property
  462. def migration_name_fragment(self):
  463. return "create_extension_%s" % self.name