django db_index迁移是否同时运行?

问题描述 投票:7回答:4

我想添加一个multi-column index to a postgres数据库。我有一个非阻塞SQL命令来执行此操作,如下所示:

CREATE INDEX CONCURRENTLY shop_product_fields_index ON shop_product (id, ...);

当我将db_index添加到我的模型并运行迁移时,它是否同时运行还是会阻止写入? django可以并发迁移吗?

django django-south django-migrations
4个回答
1
投票

在django中不支持PostgreSQL并发索引创建。

这是要求此功能的票证 - https://code.djangoproject.com/ticket/21039

但是,您可以在迁移中手动指定任何自定义RunSQL操作 - https://docs.djangoproject.com/en/1.8/ref/migration-operations/#runsql


7
投票

使用Django 1.10迁移,您可以使用RunSQL创建并发索引,并通过将atomic = False设置为迁移的数据属性,使迁移非原子化来禁用包装事务:

class Migration(migrations.Migration):
    atomic = False # disable transaction

    dependencies = []

    operations = [
        migrations.RunSQL('CREATE INDEX CONCURRENTLY ...')
    ]

1
投票

您可以使用SeparateDatabaseAndState迁移操作来提供用于创建索引的自定义SQL命令。该操作接受两个操作列表:

  • state_operations是应用于Django模型状态的操作。它们不会影响数据库。
  • 数据库操作是应用于数据库的操作。

示例迁移可能如下所示:

from django.db import migrations, models

class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [    
        migrations.SeparateDatabaseAndState(    
            state_operations=[
                # operation generated by `makemigrations` to create an ordinary index
                migrations.AlterField(
                    # ...  
                ),
            ],

            database_operations=[
                # operation to run custom SQL command (check the output of `sqlmigrate`
                # to see the auto-generated SQL, edit as needed)
                migrations.RunSQL(sql='CREATE INDEX CONCURRENTLY ...',
                                  reverse_sql='DROP INDEX ...'),
            ],
        ),
    ]

0
投票

做什么tgroshon说新的django 1.10 +

对于较小版本的django,我已经成功使用了更详细的子类化方法:

from django.db import migrations, models


class RunNonAtomicSQL(migrations.RunSQL):
    def _run_sql(self, schema_editor, sqls):
        if schema_editor.connection.in_atomic_block:
            schema_editor.atomic.__exit__(None, None, None)
        super(RunNonAtomicSQL, self)._run_sql(schema_editor, sqls)


class Migration(migrations.Migration):
    dependencies = [
    ]

    operations = [

        RunNonAtomicSQL(
            "CREATE INDEX CONCURRENTLY",
        )
    ]
© www.soinside.com 2019 - 2024. All rights reserved.