"Fossies" - the Fresh Open Source Software Archive

Member "Django-1.11.25/docs/ref/migration-operations.txt" (1 Oct 2019, 21628 Bytes) of package /linux/www/Django-1.11.25.tar.gz:

As a special service "Fossies" has tried to format the requested text file into HTML format (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "migration-operations.txt": 2.2.4_vs_2.2.5.

    1 ====================
    2 Migration Operations
    3 ====================
    5 .. module:: django.db.migrations.operations
    7 Migration files are composed of one or more ``Operation``\s, objects that
    8 declaratively record what the migration should do to your database.
   10 Django also uses these ``Operation`` objects to work out what your models
   11 looked like historically, and to calculate what changes you've made to
   12 your models since the last migration so it can automatically write
   13 your migrations; that's why they're declarative, as it means Django can
   14 easily load them all into memory and run through them without touching
   15 the database to work out what your project should look like.
   17 There are also more specialized ``Operation`` objects which are for things like
   18 :ref:`data migrations <data-migrations>` and for advanced manual database
   19 manipulation. You can also write your own ``Operation`` classes if you want
   20 to encapsulate a custom change you commonly make.
   22 If you need an empty migration file to write your own ``Operation`` objects
   23 into, just use ``python manage.py makemigrations --empty yourappname``,
   24 but be aware that manually adding schema-altering operations can confuse the
   25 migration autodetector and make resulting runs of :djadmin:`makemigrations`
   26 output incorrect code.
   28 All of the core Django operations are available from the
   29 ``django.db.migrations.operations`` module.
   31 For introductory material, see the :doc:`migrations topic guide
   32 </topics/migrations>`.
   34 Schema Operations
   35 =================
   37 ``CreateModel``
   38 ---------------
   40 .. class:: CreateModel(name, fields, options=None, bases=None, managers=None)
   42 Creates a new model in the project history and a corresponding table in the
   43 database to match it.
   45 ``name`` is the model name, as would be written in the ``models.py`` file.
   47 ``fields`` is a list of 2-tuples of ``(field_name, field_instance)``.
   48 The field instance should be an unbound field (so just
   49 ``models.CharField(...)``, rather than a field taken from another model).
   51 ``options`` is an optional dictionary of values from the model's ``Meta`` class.
   53 ``bases`` is an optional list of other classes to have this model inherit from;
   54 it can contain both class objects as well as strings in the format
   55 ``"appname.ModelName"`` if you want to depend on another model (so you inherit
   56 from the historical version). If it's not supplied, it defaults to just
   57 inheriting from the standard ``models.Model``.
   59 ``managers`` takes a list of 2-tuples of ``(manager_name, manager_instance)``.
   60 The first manager in the list will be the default manager for this model during
   61 migrations.
   63 ``DeleteModel``
   64 ---------------
   66 .. class:: DeleteModel(name)
   68 Deletes the model from the project history and its table from the database.
   70 ``RenameModel``
   71 ---------------
   73 .. class:: RenameModel(old_name, new_name)
   75 Renames the model from an old name to a new one.
   77 You may have to manually add
   78 this if you change the model's name and quite a few of its fields at once; to
   79 the autodetector, this will look like you deleted a model with the old name
   80 and added a new one with a different name, and the migration it creates will
   81 lose any data in the old table.
   83 ``AlterModelTable``
   84 -------------------
   86 .. class:: AlterModelTable(name, table)
   88 Changes the model's table name (the :attr:`~django.db.models.Options.db_table`
   89 option on the ``Meta`` subclass).
   91 ``AlterUniqueTogether``
   92 -----------------------
   94 .. class:: AlterUniqueTogether(name, unique_together)
   96 Changes the model's set of unique constraints (the
   97 :attr:`~django.db.models.Options.unique_together` option on the ``Meta``
   98 subclass).
  100 ``AlterIndexTogether``
  101 ----------------------
  103 .. class:: AlterIndexTogether(name, index_together)
  105 Changes the model's set of custom indexes (the
  106 :attr:`~django.db.models.Options.index_together` option on the ``Meta``
  107 subclass).
  109 ``AlterOrderWithRespectTo``
  110 ---------------------------
  112 .. class:: AlterOrderWithRespectTo(name, order_with_respect_to)
  114 Makes or deletes the ``_order`` column needed for the
  115 :attr:`~django.db.models.Options.order_with_respect_to` option on the ``Meta``
  116 subclass.
  118 ``AlterModelOptions``
  119 ---------------------
  121 .. class:: AlterModelOptions(name, options)
  123 Stores changes to miscellaneous model options (settings on a model's ``Meta``)
  124 like ``permissions`` and ``verbose_name``. Does not affect the database, but
  125 persists these changes for :class:`RunPython` instances to use. ``options``
  126 should be a dictionary mapping option names to values.
  128 ``AlterModelManagers``
  129 ----------------------
  131 .. class:: AlterModelManagers(name, managers)
  133 Alters the managers that are available during migrations.
  135 ``AddField``
  136 ------------
  138 .. class:: AddField(model_name, name, field, preserve_default=True)
  140 Adds a field to a model. ``model_name`` is the model's name, ``name`` is
  141 the field's name, and ``field`` is an unbound Field instance (the thing
  142 you would put in the field declaration in ``models.py`` - for example,
  143 ``models.IntegerField(null=True)``.
  145 The ``preserve_default`` argument indicates whether the field's default
  146 value is permanent and should be baked into the project state (``True``),
  147 or if it is temporary and just for this migration (``False``) - usually
  148 because the migration is adding a non-nullable field to a table and needs
  149 a default value to put into existing rows. It does not affect the behavior
  150 of setting defaults in the database directly - Django never sets database
  151 defaults and always applies them in the Django ORM code.
  153 ``RemoveField``
  154 ---------------
  156 .. class:: RemoveField(model_name, name)
  158 Removes a field from a model.
  160 Bear in mind that when reversed, this is actually adding a field to a model.
  161 The operation is reversible (apart from any data loss, which of course is
  162 irreversible) if the field is nullable or if it has a default value that can be
  163 used to populate the recreated column. If the field is not nullable and does
  164 not have a default value, the operation is irreversible.
  166 ``AlterField``
  167 --------------
  169 .. class:: AlterField(model_name, name, field, preserve_default=True)
  171 Alters a field's definition, including changes to its type,
  172 :attr:`~django.db.models.Field.null`, :attr:`~django.db.models.Field.unique`,
  173 :attr:`~django.db.models.Field.db_column` and other field attributes.
  175 The ``preserve_default`` argument indicates whether the field's default
  176 value is permanent and should be baked into the project state (``True``),
  177 or if it is temporary and just for this migration (``False``) - usually
  178 because the migration is altering a nullable field to a non-nullable one and
  179 needs a default value to put into existing rows. It does not affect the
  180 behavior of setting defaults in the database directly - Django never sets
  181 database defaults and always applies them in the Django ORM code.
  183 Note that not all changes are possible on all databases - for example, you
  184 cannot change a text-type field like ``models.TextField()`` into a number-type
  185 field like ``models.IntegerField()`` on most databases.
  187 ``RenameField``
  188 ---------------
  190 .. class:: RenameField(model_name, old_name, new_name)
  192 Changes a field's name (and, unless :attr:`~django.db.models.Field.db_column`
  193 is set, its column name).
  195 ``AddIndex``
  196 ------------
  198 .. class:: AddIndex(model_name, index)
  200 .. versionadded:: 1.11
  202 Creates an index in the database table for the model with ``model_name``.
  203 ``index`` is an instance of the :class:`~django.db.models.Index` class.
  205 ``RemoveIndex``
  206 ---------------
  208 .. class:: RemoveIndex(model_name, name)
  210 .. versionadded:: 1.11
  212 Removes the index named ``name`` from the model with ``model_name``.
  214 Special Operations
  215 ==================
  217 ``RunSQL``
  218 ----------
  220 .. class:: RunSQL(sql, reverse_sql=None, state_operations=None, hints=None, elidable=False)
  222 Allows running of arbitrary SQL on the database - useful for more advanced
  223 features of database backends that Django doesn't support directly, like
  224 partial indexes.
  226 ``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on
  227 the database. On most database backends (all but PostgreSQL), Django will
  228 split the SQL into individual statements prior to executing them. This
  229 requires installing the sqlparse_ Python library.
  231 You can also pass a list of strings or 2-tuples. The latter is used for passing
  232 queries and parameters in the same way as :ref:`cursor.execute()
  233 <executing-custom-sql>`. These three operations are equivalent::
  235     migrations.RunSQL("INSERT INTO musician (name) VALUES ('Reinhardt');")
  236     migrations.RunSQL([("INSERT INTO musician (name) VALUES ('Reinhardt');", None)])
  237     migrations.RunSQL([("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])])
  239 If you want to include literal percent signs in the query, you have to double
  240 them if you are passing parameters.
  242 The ``reverse_sql`` queries are executed when the migration is unapplied, so
  243 you can reverse the changes done in the forwards queries::
  245     migrations.RunSQL(
  246         [("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])],
  247         [("DELETE FROM musician where name=%s;", ['Reinhardt'])],
  248     )
  250 The ``state_operations`` argument is so you can supply operations that are
  251 equivalent to the SQL in terms of project state; for example, if you are
  252 manually creating a column, you should pass in a list containing an ``AddField``
  253 operation here so that the autodetector still has an up-to-date state of the
  254 model (otherwise, when you next run ``makemigrations``, it won't see any
  255 operation that adds that field and so will try to run it again). For example::
  257     migrations.RunSQL(
  258         "ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
  259         state_operations=[
  260             migrations.AddField(
  261                 'musician',
  262                 'name',
  263                 models.CharField(max_length=255),
  264             ),
  265         ],
  266     )
  268 The optional ``hints`` argument will be passed as ``**hints`` to the
  269 :meth:`allow_migrate` method of database routers to assist them in making
  270 routing decisions. See :ref:`topics-db-multi-db-hints` for more details on
  271 database hints.
  273 The optional ``elidable`` argument determines whether or not the operation will
  274 be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
  276 .. attribute:: RunSQL.noop
  278     Pass the ``RunSQL.noop`` attribute to ``sql`` or ``reverse_sql`` when you
  279     want the operation not to do anything in the given direction. This is
  280     especially useful in making the operation reversible.
  282 .. _sqlparse: https://pypi.python.org/pypi/sqlparse
  284 .. versionadded:: 1.10
  286     The ``elidable`` argument was added.
  288 ``RunPython``
  289 -------------
  291 .. class:: RunPython(code, reverse_code=None, atomic=None, hints=None, elidable=False)
  293 Runs custom Python code in a historical context. ``code`` (and ``reverse_code``
  294 if supplied) should be callable objects that accept two arguments; the first is
  295 an instance of ``django.apps.registry.Apps`` containing historical models that
  296 match the operation's place in the project history, and the second is an
  297 instance of :class:`SchemaEditor
  298 <django.db.backends.base.schema.BaseDatabaseSchemaEditor>`.
  300 The ``reverse_code`` argument is called when unapplying migrations. This
  301 callable should undo what is done in the ``code`` callable so that the
  302 migration is reversible.
  304 The optional ``hints`` argument will be passed as ``**hints`` to the
  305 :meth:`allow_migrate` method of database routers to assist them in making a
  306 routing decision. See :ref:`topics-db-multi-db-hints` for more details on
  307 database hints.
  309 The optional ``elidable`` argument determines whether or not the operation will
  310 be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
  312 You are advised to write the code as a separate function above the ``Migration``
  313 class in the migration file, and just pass it to ``RunPython``. Here's an
  314 example of using ``RunPython`` to create some initial objects on a ``Country``
  315 model::
  317     # -*- coding: utf-8 -*-
  318     from __future__ import unicode_literals
  320     from django.db import migrations
  322     def forwards_func(apps, schema_editor):
  323         # We get the model from the versioned app registry;
  324         # if we directly import it, it'll be the wrong version
  325         Country = apps.get_model("myapp", "Country")
  326         db_alias = schema_editor.connection.alias
  327         Country.objects.using(db_alias).bulk_create([
  328             Country(name="USA", code="us"),
  329             Country(name="France", code="fr"),
  330         ])
  332     def reverse_func(apps, schema_editor):
  333         # forwards_func() creates two Country instances,
  334         # so reverse_func() should delete them.
  335         Country = apps.get_model("myapp", "Country")
  336         db_alias = schema_editor.connection.alias
  337         Country.objects.using(db_alias).filter(name="USA", code="us").delete()
  338         Country.objects.using(db_alias).filter(name="France", code="fr").delete()
  340     class Migration(migrations.Migration):
  342         dependencies = []
  344         operations = [
  345             migrations.RunPython(forwards_func, reverse_func),
  346         ]
  348 This is generally the operation you would use to create
  349 :ref:`data migrations <data-migrations>`, run
  350 custom data updates and alterations, and anything else you need access to an
  351 ORM and/or Python code for.
  353 If you're upgrading from South, this is basically the South pattern as an
  354 operation - one or two methods for forwards and backwards, with an ORM and
  355 schema operations available. Most of the time, you should be able to translate
  356 the ``orm.Model`` or ``orm["appname", "Model"]`` references from South directly
  357 into ``apps.get_model("appname", "Model")`` references here and leave most of
  358 the rest of the code unchanged for data migrations. However, ``apps`` will only
  359 have references to models in the current app unless migrations in other apps
  360 are added to the migration's dependencies.
  362 Much like :class:`RunSQL`, ensure that if you change schema inside here you're
  363 either doing it outside the scope of the Django model system (e.g. triggers)
  364 or that you use :class:`SeparateDatabaseAndState` to add in operations that will
  365 reflect your changes to the model state - otherwise, the versioned ORM and
  366 the autodetector will stop working correctly.
  368 By default, ``RunPython`` will run its contents inside a transaction on
  369 databases that do not support DDL transactions (for example, MySQL and
  370 Oracle). This should be safe, but may cause a crash if you attempt to use
  371 the ``schema_editor`` provided on these backends; in this case, pass
  372 ``atomic=False`` to the ``RunPython`` operation.
  374 On databases that do support DDL transactions (SQLite and PostgreSQL),
  375 ``RunPython`` operations do not have any transactions automatically added
  376 besides the transactions created for each migration. Thus, on PostgreSQL, for
  377 example, you should avoid combining schema changes and ``RunPython`` operations
  378 in the same migration or you may hit errors like ``OperationalError: cannot
  379 ALTER TABLE "mytable" because it has pending trigger events``.
  381 If you have a different database and aren't sure if it supports DDL
  382 transactions, check the ``django.db.connection.features.can_rollback_ddl``
  383 attribute.
  385 If the ``RunPython`` operation is part of a :ref:`non-atomic migration
  386 <non-atomic-migrations>`, the operation will only be executed in a transaction
  387 if ``atomic=True`` is passed to the ``RunPython`` operation.
  389 .. warning::
  391     ``RunPython`` does not magically alter the connection of the models for you;
  392     any model methods you call will go to the default database unless you
  393     give them the current database alias (available from
  394     ``schema_editor.connection.alias``, where ``schema_editor`` is the second
  395     argument to your function).
  397 .. staticmethod:: RunPython.noop
  399     Pass the ``RunPython.noop`` method to ``code`` or ``reverse_code`` when
  400     you want the operation not to do anything in the given direction. This is
  401     especially useful in making the operation reversible.
  403 .. versionadded:: 1.10
  405     The ``elidable`` argument was added.
  407 .. versionchanged:: 1.10
  409     The ``atomic`` argument default was changed to ``None``, indicating that
  410     the atomicity is controlled by the ``atomic`` attribute of the migration.
  412 ``SeparateDatabaseAndState``
  413 ----------------------------
  415 .. class:: SeparateDatabaseAndState(database_operations=None, state_operations=None)
  417 A highly specialized operation that let you mix and match the database
  418 (schema-changing) and state (autodetector-powering) aspects of operations.
  420 It accepts two list of operations, and when asked to apply state will use the
  421 state list, and when asked to apply changes to the database will use the database
  422 list. Do not use this operation unless you're very sure you know what you're doing.
  424 .. _writing-your-own-migration-operation:
  426 Writing your own
  427 ================
  429 Operations have a relatively simple API, and they're designed so that you can
  430 easily write your own to supplement the built-in Django ones. The basic structure
  431 of an ``Operation`` looks like this::
  433     from django.db.migrations.operations.base import Operation
  435     class MyCustomOperation(Operation):
  437         # If this is False, it means that this operation will be ignored by
  438         # sqlmigrate; if true, it will be run and the SQL collected for its output.
  439         reduces_to_sql = False
  441         # If this is False, Django will refuse to reverse past this operation.
  442         reversible = False
  444         def __init__(self, arg1, arg2):
  445             # Operations are usually instantiated with arguments in migration
  446             # files. Store the values of them on self for later use.
  447             pass
  449         def state_forwards(self, app_label, state):
  450             # The Operation should take the 'state' parameter (an instance of
  451             # django.db.migrations.state.ProjectState) and mutate it to match
  452             # any schema changes that have occurred.
  453             pass
  455         def database_forwards(self, app_label, schema_editor, from_state, to_state):
  456             # The Operation should use schema_editor to apply any changes it
  457             # wants to make to the database.
  458             pass
  460         def database_backwards(self, app_label, schema_editor, from_state, to_state):
  461             # If reversible is True, this is called when the operation is reversed.
  462             pass
  464         def describe(self):
  465             # This is used to describe what the operation does in console output.
  466             return "Custom Operation"
  468 You can take this template and work from it, though we suggest looking at the
  469 built-in Django operations in ``django.db.migrations.operations`` - they're
  470 easy to read and cover a lot of the example usage of semi-internal aspects
  471 of the migration framework like ``ProjectState`` and the patterns used to get
  472 historical models, as well as ``ModelState`` and the patterns used to mutate
  473 historical models in ``state_forwards()``.
  475 Some things to note:
  477 * You don't need to learn too much about ``ProjectState`` to just write simple
  478   migrations; just know that it has an ``apps`` property that gives access to
  479   an app registry (which you can then call ``get_model`` on).
  481 * ``database_forwards`` and ``database_backwards`` both get two states passed
  482   to them; these just represent the difference the ``state_forwards`` method
  483   would have applied, but are given to you for convenience and speed reasons.
  485 * If you want to work with model classes or model instances from the
  486   ``from_state`` argument in ``database_forwards()`` or
  487   ``database_backwards()``, you must render model states using the
  488   ``clear_delayed_apps_cache()`` method to make related models available::
  490     def database_forwards(self, app_label, schema_editor, from_state, to_state):
  491         # This operation should have access to all models. Ensure that all models are
  492         # reloaded in case any are delayed.
  493         from_state.clear_delayed_apps_cache()
  494         ...
  496   .. versionadded:: 1.11
  498     This requirement and the ``clear_delayed_apps_cache()`` method is new.
  500 * ``to_state`` in the database_backwards method is the *older* state; that is,
  501   the one that will be the current state once the migration has finished reversing.
  503 * You might see implementations of ``references_model`` on the built-in
  504   operations; this is part of the autodetection code and does not matter for
  505   custom operations.
  507 .. warning::
  509     For performance reasons, the :class:`~django.db.models.Field` instances in
  510     ``ModelState.fields`` are reused across migrations. You must never change
  511     the attributes on these instances. If you need to mutate a field in
  512     ``state_forwards()``, you must remove the old instance from
  513     ``ModelState.fields`` and add a new instance in its place. The same is true
  514     for the :class:`~django.db.models.Manager` instances in
  515     ``ModelState.managers``.
  517 As a simple example, let's make an operation that loads PostgreSQL extensions
  518 (which contain some of PostgreSQL's more exciting features). It's simple enough;
  519 there's no model state changes, and all it does is run one command::
  521     from django.db.migrations.operations.base import Operation
  523     class LoadExtension(Operation):
  525         reversible = True
  527         def __init__(self, name):
  528             self.name = name
  530         def state_forwards(self, app_label, state):
  531             pass
  533         def database_forwards(self, app_label, schema_editor, from_state, to_state):
  534             schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
  536         def database_backwards(self, app_label, schema_editor, from_state, to_state):
  537             schema_editor.execute("DROP EXTENSION %s" % self.name)
  539         def describe(self):
  540             return "Creates extension %s" % self.name