Since IF EXISTS
is not supported in indexing by MySQL, you may want to write your own migration:
def drop_index_if_exists(apps, schema_editor):
# access to the connection since schema_editor.execute does not return the cursor
with schema_editor.connection.cursor() as cursor:
cursor.execute("SHOW INDEX FROM table_name WHERE KEY_NAME = 'index_name'");
exists = int(cursor.fetchone()) > 0
# outside with to close the cursor
if exists:
schema_editor.execute("CREATE INDEX index_name ON ...")
operations = [
migrations.RunPython(drop_index_if_exists)
]
For consistency, you can write a create_index_if_not_exists
method to un-apply the migration, and call it:
migrations.RunPython(drop_index_if_exists, create_index_if_not_exists)