如果存在使用django migrations.RunSQL和MySQL,我如何删除索引

时间:2017-04-27 13:07:55

标签: mysql django django-migrations

我试图使用migrations.RunSQL删除索引,但我遇到的问题不存在,有没有办法只在存在的情况下删除索引?像migrations.RunSQL(" DROP INDEX IF EXISTS index_id ON table")。

  1. Django 1.8.18
  2. MySQL 5.6
  3. 非常感谢

3 个答案:

答案 0 :(得分:1)

由于MySQL索引不支持cmake_minimum_required(VERSION 2.8.1) project(UnitTest++) option(UTPP_USE_PLUS_SIGN "Set this to OFF if you wish to use '-cpp' instead of '++' in lib/include paths" ON) option(UTPP_INCLUDE_TESTS_IN_BUILD "Set this to OFF if you do not wish to automatically build or run unit tests as part of the default cmake --build" ON) option(UTPP_AMPLIFY_WARNINGS "Set this to OFF if you wish to use CMake default warning levels; should generally only use to work around support issues for your specific compiler" ON) ... # up warning level for project if (${UTPP_AMPLIFY_WARNINGS}) # instead of getting compiler specific, we're going to try making an assumption that an existing /W# means # we are dealing with an MSVC or MSVC-like compiler (e.g. Intel on Windows) if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") # message(STATUS "CMAKE_CXX_FLAGS MATCHES") string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /WX") else() # message(STATUS "set(CMAKE_CXX_FLAGS") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror") endif() endif() ,您可能需要编写自己的迁移:

IF EXISTS

为了保持一致性,您可以编写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) ] 方法来取消应用迁移,并将其命名为:

create_index_if_not_exists

答案 1 :(得分:0)

这里有一个解决方案,谢谢你的想法@ alfonso.kim

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations


def drop_index_if_exists_and_create(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 = True if cursor.fetchone() else False
    # outside with to close the cursor
    if exists:
        schema_editor.execute("DROP INDEX index_name ON table_name")

    schema_editor.execute("CREATE INDEX index_name ON table_name(index_name(191))")


class Migration(migrations.Migration):

    dependencies = [
        ('table_name', ''),
    ]

    operations = [
        migrations.RunPython(drop_index_if_exists_and_create)
    ]

答案 2 :(得分:0)

执行您的代码后出现交易错误:

django.db.transaction.TransactionManagementError: Executing DDL statements while in a transaction on databases that can't perform a rollback is prohibited.

Django 2.5 MySql 5.7