2014-02-13 02:53:35 +08:00
|
|
|
====================
|
|
|
|
Migration Operations
|
|
|
|
====================
|
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. module:: django.db.migrations.operations
|
|
|
|
|
|
|
|
Migration files are composed of one or more ``Operation``\s, objects that
|
2014-02-13 02:53:35 +08:00
|
|
|
declaratively record what the migration should do to your database.
|
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Django also uses these ``Operation`` objects to work out what your models
|
2014-02-13 02:53:35 +08:00
|
|
|
looked like historically, and to calculate what changes you've made to
|
|
|
|
your models since the last migration so it can automatically write
|
|
|
|
your migrations; that's why they're declarative, as it means Django can
|
|
|
|
easily load them all into memory and run through them without touching
|
|
|
|
the database to work out what your project should look like.
|
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
There are also more specialized ``Operation`` objects which are for things like
|
2014-02-13 02:53:35 +08:00
|
|
|
:ref:`data migrations <data-migrations>` and for advanced manual database
|
2014-04-28 03:05:25 +08:00
|
|
|
manipulation. You can also write your own ``Operation`` classes if you want
|
2014-02-13 02:53:35 +08:00
|
|
|
to encapsulate a custom change you commonly make.
|
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
If you need an empty migration file to write your own ``Operation`` objects
|
2019-06-17 22:54:55 +08:00
|
|
|
into, use ``python manage.py makemigrations --empty yourappname``, but be aware
|
|
|
|
that manually adding schema-altering operations can confuse the migration
|
|
|
|
autodetector and make resulting runs of :djadmin:`makemigrations` output
|
|
|
|
incorrect code.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
All of the core Django operations are available from the
|
|
|
|
``django.db.migrations.operations`` module.
|
|
|
|
|
2014-09-28 06:12:34 +08:00
|
|
|
For introductory material, see the :doc:`migrations topic guide
|
|
|
|
</topics/migrations>`.
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
Schema Operations
|
|
|
|
=================
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``CreateModel``
|
|
|
|
---------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-12-13 06:19:58 +08:00
|
|
|
.. class:: CreateModel(name, fields, options=None, bases=None, managers=None)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Creates a new model in the project history and a corresponding table in the
|
|
|
|
database to match it.
|
|
|
|
|
|
|
|
``name`` is the model name, as would be written in the ``models.py`` file.
|
|
|
|
|
|
|
|
``fields`` is a list of 2-tuples of ``(field_name, field_instance)``.
|
2015-11-15 06:19:45 +08:00
|
|
|
The field instance should be an unbound field (so just
|
|
|
|
``models.CharField(...)``, rather than a field taken from another model).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
``options`` is an optional dictionary of values from the model's ``Meta`` class.
|
|
|
|
|
2014-03-01 00:44:03 +08:00
|
|
|
``bases`` is an optional list of other classes to have this model inherit from;
|
2014-02-13 02:53:35 +08:00
|
|
|
it can contain both class objects as well as strings in the format
|
|
|
|
``"appname.ModelName"`` if you want to depend on another model (so you inherit
|
2019-06-17 22:54:55 +08:00
|
|
|
from the historical version). If it's not supplied, it defaults to inheriting
|
|
|
|
from the standard ``models.Model``.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-12-13 06:19:58 +08:00
|
|
|
``managers`` takes a list of 2-tuples of ``(manager_name, manager_instance)``.
|
|
|
|
The first manager in the list will be the default manager for this model during
|
|
|
|
migrations.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``DeleteModel``
|
|
|
|
---------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: DeleteModel(name)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Deletes the model from the project history and its table from the database.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``RenameModel``
|
|
|
|
---------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: RenameModel(old_name, new_name)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Renames the model from an old name to a new one.
|
|
|
|
|
|
|
|
You may have to manually add
|
|
|
|
this if you change the model's name and quite a few of its fields at once; to
|
|
|
|
the autodetector, this will look like you deleted a model with the old name
|
|
|
|
and added a new one with a different name, and the migration it creates will
|
|
|
|
lose any data in the old table.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterModelTable``
|
|
|
|
-------------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: AlterModelTable(name, table)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Changes the model's table name (the :attr:`~django.db.models.Options.db_table`
|
|
|
|
option on the ``Meta`` subclass).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterUniqueTogether``
|
|
|
|
-----------------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: AlterUniqueTogether(name, unique_together)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Changes the model's set of unique constraints (the
|
|
|
|
:attr:`~django.db.models.Options.unique_together` option on the ``Meta``
|
|
|
|
subclass).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterIndexTogether``
|
|
|
|
----------------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: AlterIndexTogether(name, index_together)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Changes the model's set of custom indexes (the
|
|
|
|
:attr:`~django.db.models.Options.index_together` option on the ``Meta``
|
|
|
|
subclass).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterOrderWithRespectTo``
|
|
|
|
---------------------------
|
2014-06-16 05:55:44 +08:00
|
|
|
|
2014-07-24 05:31:31 +08:00
|
|
|
.. class:: AlterOrderWithRespectTo(name, order_with_respect_to)
|
2014-06-16 05:55:44 +08:00
|
|
|
|
|
|
|
Makes or deletes the ``_order`` column needed for the
|
|
|
|
:attr:`~django.db.models.Options.order_with_respect_to` option on the ``Meta``
|
|
|
|
subclass.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterModelOptions``
|
|
|
|
---------------------
|
2014-06-16 05:55:44 +08:00
|
|
|
|
2014-07-24 05:31:31 +08:00
|
|
|
.. class:: AlterModelOptions(name, options)
|
2014-06-16 05:55:44 +08:00
|
|
|
|
|
|
|
Stores changes to miscellaneous model options (settings on a model's ``Meta``)
|
|
|
|
like ``permissions`` and ``verbose_name``. Does not affect the database, but
|
2014-07-24 05:31:31 +08:00
|
|
|
persists these changes for :class:`RunPython` instances to use. ``options``
|
|
|
|
should be a dictionary mapping option names to values.
|
2014-06-16 05:55:44 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterModelManagers``
|
|
|
|
----------------------
|
2014-12-13 06:19:58 +08:00
|
|
|
|
|
|
|
.. class:: AlterModelManagers(name, managers)
|
|
|
|
|
|
|
|
Alters the managers that are available during migrations.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AddField``
|
|
|
|
------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: AddField(model_name, name, field, preserve_default=True)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Adds a field to a model. ``model_name`` is the model's name, ``name`` is
|
|
|
|
the field's name, and ``field`` is an unbound Field instance (the thing
|
|
|
|
you would put in the field declaration in ``models.py`` - for example,
|
|
|
|
``models.IntegerField(null=True)``.
|
|
|
|
|
|
|
|
The ``preserve_default`` argument indicates whether the field's default
|
|
|
|
value is permanent and should be baked into the project state (``True``),
|
|
|
|
or if it is temporary and just for this migration (``False``) - usually
|
|
|
|
because the migration is adding a non-nullable field to a table and needs
|
2015-09-26 05:47:36 +08:00
|
|
|
a default value to put into existing rows. It does not affect the behavior
|
2014-02-13 02:53:35 +08:00
|
|
|
of setting defaults in the database directly - Django never sets database
|
2014-10-07 07:53:21 +08:00
|
|
|
defaults and always applies them in the Django ORM code.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2019-10-04 21:55:41 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
On older databases, adding a field with a default value may cause a full
|
|
|
|
rewrite of the table. This happens even for nullable fields and may have a
|
|
|
|
negative performance impact. To avoid that, the following steps should be
|
|
|
|
taken.
|
|
|
|
|
|
|
|
* Add the nullable field without the default value and run the
|
|
|
|
:djadmin:`makemigrations` command. This should generate a migration with
|
|
|
|
an ``AddField`` operation.
|
|
|
|
|
|
|
|
* Add the default value to your field and run the :djadmin:`makemigrations`
|
|
|
|
command. This should generate a migration with an ``AlterField``
|
|
|
|
operation.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``RemoveField``
|
|
|
|
---------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: RemoveField(model_name, name)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Removes a field from a model.
|
|
|
|
|
2016-01-29 01:47:08 +08:00
|
|
|
Bear in mind that when reversed, this is actually adding a field to a model.
|
2020-05-01 20:37:21 +08:00
|
|
|
The operation is reversible (apart from any data loss, which is irreversible)
|
|
|
|
if the field is nullable or if it has a default value that can be used to
|
|
|
|
populate the recreated column. If the field is not nullable and does not have a
|
|
|
|
default value, the operation is irreversible.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``AlterField``
|
|
|
|
--------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-10-07 07:53:21 +08:00
|
|
|
.. class:: AlterField(model_name, name, field, preserve_default=True)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Alters a field's definition, including changes to its type,
|
|
|
|
:attr:`~django.db.models.Field.null`, :attr:`~django.db.models.Field.unique`,
|
|
|
|
:attr:`~django.db.models.Field.db_column` and other field attributes.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-10-07 07:53:21 +08:00
|
|
|
The ``preserve_default`` argument indicates whether the field's default
|
|
|
|
value is permanent and should be baked into the project state (``True``),
|
|
|
|
or if it is temporary and just for this migration (``False``) - usually
|
|
|
|
because the migration is altering a nullable field to a non-nullable one and
|
2015-09-26 05:47:36 +08:00
|
|
|
needs a default value to put into existing rows. It does not affect the
|
2014-10-07 07:53:21 +08:00
|
|
|
behavior of setting defaults in the database directly - Django never sets
|
|
|
|
database defaults and always applies them in the Django ORM code.
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
Note that not all changes are possible on all databases - for example, you
|
|
|
|
cannot change a text-type field like ``models.TextField()`` into a number-type
|
|
|
|
field like ``models.IntegerField()`` on most databases.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``RenameField``
|
|
|
|
---------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
.. class:: RenameField(model_name, old_name, new_name)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Changes a field's name (and, unless :attr:`~django.db.models.Field.db_column`
|
|
|
|
is set, its column name).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-06-26 00:32:56 +08:00
|
|
|
``AddIndex``
|
|
|
|
------------
|
|
|
|
|
|
|
|
.. class:: AddIndex(model_name, index)
|
|
|
|
|
|
|
|
Creates an index in the database table for the model with ``model_name``.
|
|
|
|
``index`` is an instance of the :class:`~django.db.models.Index` class.
|
|
|
|
|
|
|
|
``RemoveIndex``
|
|
|
|
---------------
|
|
|
|
|
|
|
|
.. class:: RemoveIndex(model_name, name)
|
|
|
|
|
|
|
|
Removes the index named ``name`` from the model with ``model_name``.
|
|
|
|
|
2016-11-05 21:12:12 +08:00
|
|
|
``AddConstraint``
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
.. class:: AddConstraint(model_name, constraint)
|
|
|
|
|
2019-08-11 01:08:00 +08:00
|
|
|
Creates a :doc:`constraint </ref/models/constraints>` in the database table for
|
|
|
|
the model with ``model_name``.
|
2016-11-05 21:12:12 +08:00
|
|
|
|
|
|
|
``RemoveConstraint``
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
.. class:: RemoveConstraint(model_name, name)
|
|
|
|
|
|
|
|
Removes the constraint named ``name`` from the model with ``model_name``.
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
Special Operations
|
|
|
|
==================
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``RunSQL``
|
|
|
|
----------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-09 16:12:46 +08:00
|
|
|
.. class:: RunSQL(sql, reverse_sql=None, state_operations=None, hints=None, elidable=False)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-23 07:05:14 +08:00
|
|
|
Allows running of arbitrary SQL on the database - useful for more advanced
|
2020-03-01 03:35:11 +08:00
|
|
|
features of database backends that Django doesn't support directly.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2014-04-26 16:22:48 +08:00
|
|
|
``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on
|
|
|
|
the database. On most database backends (all but PostgreSQL), Django will
|
2018-11-10 08:09:36 +08:00
|
|
|
split the SQL into individual statements prior to executing them.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2020-04-01 16:58:41 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
On PostgreSQL and SQLite, only use ``BEGIN`` or ``COMMIT`` in your SQL in
|
|
|
|
:ref:`non-atomic migrations <non-atomic-migrations>`, to avoid breaking
|
|
|
|
Django's transaction state.
|
|
|
|
|
2014-09-16 08:25:02 +08:00
|
|
|
You can also pass a list of strings or 2-tuples. The latter is used for passing
|
|
|
|
queries and parameters in the same way as :ref:`cursor.execute()
|
|
|
|
<executing-custom-sql>`. These three operations are equivalent::
|
|
|
|
|
|
|
|
migrations.RunSQL("INSERT INTO musician (name) VALUES ('Reinhardt');")
|
2015-09-19 10:35:28 +08:00
|
|
|
migrations.RunSQL([("INSERT INTO musician (name) VALUES ('Reinhardt');", None)])
|
|
|
|
migrations.RunSQL([("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])])
|
2014-09-16 08:25:02 +08:00
|
|
|
|
|
|
|
If you want to include literal percent signs in the query, you have to double
|
|
|
|
them if you are passing parameters.
|
|
|
|
|
2020-03-25 21:37:54 +08:00
|
|
|
The ``reverse_sql`` queries are executed when the migration is unapplied. They
|
|
|
|
should undo what is done by the ``sql`` queries. For example, to undo the above
|
|
|
|
insertion with a deletion::
|
2015-09-09 18:26:09 +08:00
|
|
|
|
|
|
|
migrations.RunSQL(
|
2020-03-25 21:37:54 +08:00
|
|
|
sql=[("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])],
|
|
|
|
reverse_sql=[("DELETE FROM musician where name=%s;", ['Reinhardt'])],
|
2015-09-09 18:26:09 +08:00
|
|
|
)
|
|
|
|
|
2020-03-25 21:37:54 +08:00
|
|
|
If ``reverse_sql`` is ``None`` (the default), the ``RunSQL`` operation is
|
|
|
|
irreversible.
|
|
|
|
|
2020-04-01 16:58:41 +08:00
|
|
|
The ``state_operations`` argument allows you to supply operations that are
|
|
|
|
equivalent to the SQL in terms of project state. For example, if you are
|
2014-02-13 02:53:35 +08:00
|
|
|
manually creating a column, you should pass in a list containing an ``AddField``
|
|
|
|
operation here so that the autodetector still has an up-to-date state of the
|
2020-04-01 16:58:41 +08:00
|
|
|
model. If you don't, when you next run ``makemigrations``, it won't see any
|
|
|
|
operation that adds that field and so will try to run it again. For example::
|
2015-12-15 21:06:33 +08:00
|
|
|
|
|
|
|
migrations.RunSQL(
|
|
|
|
"ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
|
|
|
|
state_operations=[
|
|
|
|
migrations.AddField(
|
|
|
|
'musician',
|
|
|
|
'name',
|
|
|
|
models.CharField(max_length=255),
|
|
|
|
),
|
|
|
|
],
|
|
|
|
)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2015-01-09 01:10:10 +08:00
|
|
|
The optional ``hints`` argument will be passed as ``**hints`` to the
|
|
|
|
:meth:`allow_migrate` method of database routers to assist them in making
|
|
|
|
routing decisions. See :ref:`topics-db-multi-db-hints` for more details on
|
|
|
|
database hints.
|
|
|
|
|
2016-01-09 16:12:46 +08:00
|
|
|
The optional ``elidable`` argument determines whether or not the operation will
|
|
|
|
be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
|
|
|
|
|
2015-01-09 01:00:04 +08:00
|
|
|
.. attribute:: RunSQL.noop
|
|
|
|
|
|
|
|
Pass the ``RunSQL.noop`` attribute to ``sql`` or ``reverse_sql`` when you
|
|
|
|
want the operation not to do anything in the given direction. This is
|
|
|
|
especially useful in making the operation reversible.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``RunPython``
|
|
|
|
-------------
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-01-31 04:46:28 +08:00
|
|
|
.. class:: RunPython(code, reverse_code=None, atomic=None, hints=None, elidable=False)
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Runs custom Python code in a historical context. ``code`` (and ``reverse_code``
|
|
|
|
if supplied) should be callable objects that accept two arguments; the first is
|
|
|
|
an instance of ``django.apps.registry.Apps`` containing historical models that
|
|
|
|
match the operation's place in the project history, and the second is an
|
2014-04-28 03:05:25 +08:00
|
|
|
instance of :class:`SchemaEditor
|
2015-01-13 04:20:40 +08:00
|
|
|
<django.db.backends.base.schema.BaseDatabaseSchemaEditor>`.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2015-09-09 18:26:09 +08:00
|
|
|
The ``reverse_code`` argument is called when unapplying migrations. This
|
|
|
|
callable should undo what is done in the ``code`` callable so that the
|
2020-03-25 21:37:54 +08:00
|
|
|
migration is reversible. If ``reverse_code`` is ``None`` (the default), the
|
|
|
|
``RunPython`` operation is irreversible.
|
2015-09-09 18:26:09 +08:00
|
|
|
|
2015-01-09 01:10:10 +08:00
|
|
|
The optional ``hints`` argument will be passed as ``**hints`` to the
|
|
|
|
:meth:`allow_migrate` method of database routers to assist them in making a
|
|
|
|
routing decision. See :ref:`topics-db-multi-db-hints` for more details on
|
|
|
|
database hints.
|
|
|
|
|
2016-01-09 16:12:46 +08:00
|
|
|
The optional ``elidable`` argument determines whether or not the operation will
|
|
|
|
be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
You are advised to write the code as a separate function above the ``Migration``
|
2019-06-17 22:54:55 +08:00
|
|
|
class in the migration file, and pass it to ``RunPython``. Here's an example of
|
|
|
|
using ``RunPython`` to create some initial objects on a ``Country`` model::
|
2014-04-15 01:07:02 +08:00
|
|
|
|
2017-01-21 20:40:33 +08:00
|
|
|
from django.db import migrations
|
2014-04-15 01:07:02 +08:00
|
|
|
|
|
|
|
def forwards_func(apps, schema_editor):
|
|
|
|
# We get the model from the versioned app registry;
|
|
|
|
# if we directly import it, it'll be the wrong version
|
|
|
|
Country = apps.get_model("myapp", "Country")
|
2014-06-09 10:30:15 +08:00
|
|
|
db_alias = schema_editor.connection.alias
|
2014-08-16 01:29:01 +08:00
|
|
|
Country.objects.using(db_alias).bulk_create([
|
|
|
|
Country(name="USA", code="us"),
|
|
|
|
Country(name="France", code="fr"),
|
|
|
|
])
|
2014-04-15 01:07:02 +08:00
|
|
|
|
2015-09-09 18:26:09 +08:00
|
|
|
def reverse_func(apps, schema_editor):
|
|
|
|
# forwards_func() creates two Country instances,
|
|
|
|
# so reverse_func() should delete them.
|
|
|
|
Country = apps.get_model("myapp", "Country")
|
|
|
|
db_alias = schema_editor.connection.alias
|
|
|
|
Country.objects.using(db_alias).filter(name="USA", code="us").delete()
|
|
|
|
Country.objects.using(db_alias).filter(name="France", code="fr").delete()
|
|
|
|
|
2014-04-15 01:07:02 +08:00
|
|
|
class Migration(migrations.Migration):
|
|
|
|
|
|
|
|
dependencies = []
|
|
|
|
|
|
|
|
operations = [
|
2015-09-09 18:26:09 +08:00
|
|
|
migrations.RunPython(forwards_func, reverse_func),
|
2014-04-15 01:07:02 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
This is generally the operation you would use to create
|
|
|
|
:ref:`data migrations <data-migrations>`, run
|
|
|
|
custom data updates and alterations, and anything else you need access to an
|
2015-06-05 20:24:53 +08:00
|
|
|
ORM and/or Python code for.
|
2014-04-15 01:07:02 +08:00
|
|
|
|
2014-04-28 03:05:25 +08:00
|
|
|
Much like :class:`RunSQL`, ensure that if you change schema inside here you're
|
2014-04-15 01:07:02 +08:00
|
|
|
either doing it outside the scope of the Django model system (e.g. triggers)
|
2014-09-02 20:12:19 +08:00
|
|
|
or that you use :class:`SeparateDatabaseAndState` to add in operations that will
|
|
|
|
reflect your changes to the model state - otherwise, the versioned ORM and
|
|
|
|
the autodetector will stop working correctly.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2015-05-13 20:19:51 +08:00
|
|
|
By default, ``RunPython`` will run its contents inside a transaction on
|
|
|
|
databases that do not support DDL transactions (for example, MySQL and
|
2014-05-08 05:28:34 +08:00
|
|
|
Oracle). This should be safe, but may cause a crash if you attempt to use
|
2015-05-13 20:19:51 +08:00
|
|
|
the ``schema_editor`` provided on these backends; in this case, pass
|
|
|
|
``atomic=False`` to the ``RunPython`` operation.
|
|
|
|
|
|
|
|
On databases that do support DDL transactions (SQLite and PostgreSQL),
|
|
|
|
``RunPython`` operations do not have any transactions automatically added
|
2016-01-31 04:46:28 +08:00
|
|
|
besides the transactions created for each migration. Thus, on PostgreSQL, for
|
|
|
|
example, you should avoid combining schema changes and ``RunPython`` operations
|
|
|
|
in the same migration or you may hit errors like ``OperationalError: cannot
|
|
|
|
ALTER TABLE "mytable" because it has pending trigger events``.
|
2015-05-13 20:19:51 +08:00
|
|
|
|
|
|
|
If you have a different database and aren't sure if it supports DDL
|
|
|
|
transactions, check the ``django.db.connection.features.can_rollback_ddl``
|
|
|
|
attribute.
|
2014-05-08 05:28:34 +08:00
|
|
|
|
2016-01-31 04:46:28 +08:00
|
|
|
If the ``RunPython`` operation is part of a :ref:`non-atomic migration
|
|
|
|
<non-atomic-migrations>`, the operation will only be executed in a transaction
|
|
|
|
if ``atomic=True`` is passed to the ``RunPython`` operation.
|
|
|
|
|
2014-06-09 10:30:15 +08:00
|
|
|
.. warning::
|
|
|
|
|
2014-06-10 00:09:16 +08:00
|
|
|
``RunPython`` does not magically alter the connection of the models for you;
|
2014-06-09 10:30:15 +08:00
|
|
|
any model methods you call will go to the default database unless you
|
|
|
|
give them the current database alias (available from
|
|
|
|
``schema_editor.connection.alias``, where ``schema_editor`` is the second
|
|
|
|
argument to your function).
|
|
|
|
|
2015-01-09 01:00:04 +08:00
|
|
|
.. staticmethod:: RunPython.noop
|
|
|
|
|
|
|
|
Pass the ``RunPython.noop`` method to ``code`` or ``reverse_code`` when
|
|
|
|
you want the operation not to do anything in the given direction. This is
|
|
|
|
especially useful in making the operation reversible.
|
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
``SeparateDatabaseAndState``
|
|
|
|
----------------------------
|
2014-09-02 20:12:19 +08:00
|
|
|
|
|
|
|
.. class:: SeparateDatabaseAndState(database_operations=None, state_operations=None)
|
|
|
|
|
2020-03-04 01:51:39 +08:00
|
|
|
A highly specialized operation that lets you mix and match the database
|
2014-09-02 20:12:19 +08:00
|
|
|
(schema-changing) and state (autodetector-powering) aspects of operations.
|
|
|
|
|
2020-03-04 01:51:39 +08:00
|
|
|
It accepts two lists of operations. When asked to apply state, it will use the
|
|
|
|
``state_operations`` list (this is a generalized version of :class:`RunSQL`'s
|
|
|
|
``state_operations`` argument). When asked to apply changes to the database, it
|
|
|
|
will use the ``database_operations`` list.
|
|
|
|
|
|
|
|
If the actual state of the database and Django's view of the state get out of
|
|
|
|
sync, this can break the migration framework, even leading to data loss. It's
|
|
|
|
worth exercising caution and checking your database and state operations
|
|
|
|
carefully. You can use :djadmin:`sqlmigrate` and :djadmin:`dbshell` to check
|
|
|
|
your database operations. You can use :djadmin:`makemigrations`, especially
|
|
|
|
with :option:`--dry-run<makemigrations --dry-run>`, to check your state
|
|
|
|
operations.
|
|
|
|
|
|
|
|
For an example using ``SeparateDatabaseAndState``, see
|
|
|
|
:ref:`changing-a-manytomanyfield-to-use-a-through-model`.
|
2014-09-02 20:12:19 +08:00
|
|
|
|
2016-11-06 19:03:05 +08:00
|
|
|
.. _writing-your-own-migration-operation:
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
Writing your own
|
|
|
|
================
|
|
|
|
|
|
|
|
Operations have a relatively simple API, and they're designed so that you can
|
2019-06-17 22:54:55 +08:00
|
|
|
easily write your own to supplement the built-in Django ones. The basic
|
|
|
|
structure of an ``Operation`` looks like this::
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
from django.db.migrations.operations.base import Operation
|
|
|
|
|
|
|
|
class MyCustomOperation(Operation):
|
|
|
|
|
|
|
|
# If this is False, it means that this operation will be ignored by
|
|
|
|
# sqlmigrate; if true, it will be run and the SQL collected for its output.
|
|
|
|
reduces_to_sql = False
|
|
|
|
|
|
|
|
# If this is False, Django will refuse to reverse past this operation.
|
|
|
|
reversible = False
|
|
|
|
|
|
|
|
def __init__(self, arg1, arg2):
|
|
|
|
# Operations are usually instantiated with arguments in migration
|
|
|
|
# files. Store the values of them on self for later use.
|
|
|
|
pass
|
|
|
|
|
|
|
|
def state_forwards(self, app_label, state):
|
|
|
|
# The Operation should take the 'state' parameter (an instance of
|
|
|
|
# django.db.migrations.state.ProjectState) and mutate it to match
|
|
|
|
# any schema changes that have occurred.
|
|
|
|
pass
|
|
|
|
|
|
|
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
|
|
|
# The Operation should use schema_editor to apply any changes it
|
|
|
|
# wants to make to the database.
|
|
|
|
pass
|
|
|
|
|
|
|
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
|
|
|
# If reversible is True, this is called when the operation is reversed.
|
|
|
|
pass
|
|
|
|
|
|
|
|
def describe(self):
|
|
|
|
# This is used to describe what the operation does in console output.
|
|
|
|
return "Custom Operation"
|
|
|
|
|
2019-11-23 19:08:45 +08:00
|
|
|
@property
|
|
|
|
def migration_name_fragment(self):
|
|
|
|
# Optional. A filename part suitable for automatically naming a
|
|
|
|
# migration containing this operation, or None if not applicable.
|
|
|
|
return "custom_operation_%s_%s" % (self.arg1, self.arg2)
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
You can take this template and work from it, though we suggest looking at the
|
2019-06-17 22:54:55 +08:00
|
|
|
built-in Django operations in ``django.db.migrations.operations`` - they cover
|
|
|
|
a lot of the example usage of semi-internal aspects of the migration framework
|
|
|
|
like ``ProjectState`` and the patterns used to get historical models, as well
|
|
|
|
as ``ModelState`` and the patterns used to mutate historical models in
|
|
|
|
``state_forwards()``.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
Some things to note:
|
|
|
|
|
2019-06-17 22:54:55 +08:00
|
|
|
* You don't need to learn too much about ``ProjectState`` to write migrations;
|
|
|
|
just know that it has an ``apps`` property that gives access to an app
|
|
|
|
registry (which you can then call ``get_model`` on).
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
* ``database_forwards`` and ``database_backwards`` both get two states passed
|
2019-06-17 22:54:55 +08:00
|
|
|
to them; these represent the difference the ``state_forwards`` method would
|
|
|
|
have applied, but are given to you for convenience and speed reasons.
|
2014-02-13 02:53:35 +08:00
|
|
|
|
2016-11-06 19:03:05 +08:00
|
|
|
* If you want to work with model classes or model instances from the
|
|
|
|
``from_state`` argument in ``database_forwards()`` or
|
|
|
|
``database_backwards()``, you must render model states using the
|
|
|
|
``clear_delayed_apps_cache()`` method to make related models available::
|
|
|
|
|
|
|
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
|
|
|
# This operation should have access to all models. Ensure that all models are
|
|
|
|
# reloaded in case any are delayed.
|
|
|
|
from_state.clear_delayed_apps_cache()
|
|
|
|
...
|
|
|
|
|
2014-02-13 02:53:35 +08:00
|
|
|
* ``to_state`` in the database_backwards method is the *older* state; that is,
|
|
|
|
the one that will be the current state once the migration has finished reversing.
|
|
|
|
|
|
|
|
* You might see implementations of ``references_model`` on the built-in
|
|
|
|
operations; this is part of the autodetection code and does not matter for
|
|
|
|
custom operations.
|
|
|
|
|
2015-04-07 02:17:13 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
For performance reasons, the :class:`~django.db.models.Field` instances in
|
|
|
|
``ModelState.fields`` are reused across migrations. You must never change
|
|
|
|
the attributes on these instances. If you need to mutate a field in
|
|
|
|
``state_forwards()``, you must remove the old instance from
|
|
|
|
``ModelState.fields`` and add a new instance in its place. The same is true
|
|
|
|
for the :class:`~django.db.models.Manager` instances in
|
|
|
|
``ModelState.managers``.
|
|
|
|
|
2019-06-17 22:54:55 +08:00
|
|
|
As an example, let's make an operation that loads PostgreSQL extensions (which
|
|
|
|
contain some of PostgreSQL's more exciting features). Since there's no model
|
|
|
|
state changes, all it does is run one command::
|
2014-02-13 02:53:35 +08:00
|
|
|
|
|
|
|
from django.db.migrations.operations.base import Operation
|
|
|
|
|
|
|
|
class LoadExtension(Operation):
|
|
|
|
|
|
|
|
reversible = True
|
|
|
|
|
|
|
|
def __init__(self, name):
|
|
|
|
self.name = name
|
|
|
|
|
|
|
|
def state_forwards(self, app_label, state):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
|
|
|
schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
|
|
|
|
|
|
|
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
|
|
|
schema_editor.execute("DROP EXTENSION %s" % self.name)
|
|
|
|
|
|
|
|
def describe(self):
|
|
|
|
return "Creates extension %s" % self.name
|
2019-11-23 19:08:45 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def migration_name_fragment(self):
|
|
|
|
return "create_extension_%s" % self.name
|