db.migrations.operations.RunSQL

class RunSQL(sql, reverse_sql=None, state_operations=None, hints=None, elidable=False) [source]

Allows running of arbitrary SQL on the database - useful for more advanced features of database backends that Django doesn’t support directly, like partial indexes.

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 split the SQL into individual statements prior to executing them. This requires installing the sqlparse Python library.

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 cursor.execute(). These three operations are equivalent:

migrations.RunSQL("INSERT INTO musician (name) VALUES ('Reinhardt');")
migrations.RunSQL([("INSERT INTO musician (name) VALUES ('Reinhardt');", None)])
migrations.RunSQL([("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])])

If you want to include literal percent signs in the query, you have to double them if you are passing parameters.

The reverse_sql queries are executed when the migration is unapplied, so you can reverse the changes done in the forwards queries:

migrations.RunSQL(
    [("INSERT INTO musician (name) VALUES (%s);", ['Reinhardt'])],
    [("DELETE FROM musician where name=%s;", ['Reinhardt'])],
)

The state_operations argument is so you can supply operations that are equivalent to the SQL in terms of project state; for example, if you are 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 model (otherwise, 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:

migrations.RunSQL(
    "ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
    state_operations=[
        migrations.AddField(
            'musician',
            'name',
            models.CharField(max_length=255),
        ),
    ],
)

The optional hints argument will be passed as **hints to the allow_migrate() method of database routers to assist them in making routing decisions. See Hints for more details on database hints.

The optional elidable argument determines whether or not the operation will be removed (elided) when squashing migrations.

doc_Django
2016-10-09 18:35:11
Comments
Leave a Comment

Please login to continue.