加速大型数据库上的 Django 迁移

Speed up Django Migrations on Large Database

我有一个 MySQL 数据库,其中有多个 table,每个数据库都有近 2M 条记录。当我 运行 更新那些 table 的迁移时,它非常慢。我尝试将服务器增强到 64 CPU 和 240GB RAM(可能真的没有必要),但它仍然花费太长时间。

有什么方法可以加快迁移速度吗?

编辑:正如@iklinac 所指出的,我看到这个 post 关于创建一个新的临时 table 然后将数据从旧的 table 迁移到这个新的 table。有没有 "Django way" 可以做到这一点?

您可以 运行 SQL 通过 writing migrations or editing migration file yourself using RunSQL 操作在 Django 迁移中进行查询

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

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

带有 state_operations 个参数

state_operations argument allows you to 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. 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:

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