我如何告诉 django 如何恢复自定义迁移?

问题描述 投票:0回答:1

我有两个简单的迁移:

0001_initial.py

# Generated by Django 4.2.7 on 2023-11-30 11:15

from django.db import migrations, models


class Migration(migrations.Migration):
    initial = True

    dependencies = []

    operations = [
        migrations.RunSQL(
            """
            CREATE TABLE comments (
                id SERIAL PRIMARY KEY,
                contents VARCHAR(240) NOT NULL 
            );
            """
        ),
    ]

0002.py

# Generated by Django 4.2.7 on 2023-11-30 11:15

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("polls", "0001_initial")
    ]

    operations = [
        migrations.RunSQL(
            """
            ALTER TABLE comments RENAME COLUMN contents to text;
            """
        ),
    ]

我跑步:

python管理.py迁移

然后我想撤消0002迁移

我跑步

python manage.py 迁移民意调查 0001

但是 Django 不知道如何撤消第二次迁移中的更改。

我如何告诉 Django,为了撤消 0002 迁移中的更改,我需要运行此 SQL:

ALTER TABLE comments RENAME COLUMN text to contents;

我尝试搜索但没有成功。

django migration
1个回答
0
投票

RunSQL
迁移[Django-doc]采用第二个可选参数,您可以在其中指定反向迁移,因此:

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunSQL(
            'ALTER TABLE comments RENAME COLUMN contents TO text;',
            'ALTER TABLE comments RENAME COLUMN text TO contents;',
        ),
    ]

如果您随后迁移至:

manage.py migrate polls 0001

它将查看所有迁移是否都有反向操作,并接受该查询。

© www.soinside.com 2019 - 2024. All rights reserved.