gpt4 book ai didi

django - 如何忽略特定的迁移?

转载 作者:行者123 更新时间:2023-12-02 16:51:28 24 4
gpt4 key购买 nike

我有这样的迁移:

class Migration(migrations.Migration):

dependencies = [
('app', '0020_auto_20191023_2245'),
]

operations = [
migrations.AddField(
model_name='agenda',
name='theme',
field=models.PositiveIntegerField(default=1),
),
]

但是它引发了一个错误:

django.db.utils.ProgrammingError: column "theme" of relation "app_agenda" already exists

没问题,我已经像这样包装了这个错误:

from django.db import migrations, models, ProgrammingError


def add_field_theme_to_agenda(apps, schema_editor):
try:
migrations.AddField(
model_name='agenda',
name='theme',
field=models.PositiveIntegerField(default=1),
),
except ProgrammingError as e: # sometimes it can exist
if "already exists" not in str(e):
raise


class Migration(migrations.Migration):
dependencies = [
('app', '0020_auto_20191023_2245'),
]
operations = [
migrations.RunPython(add_field_theme_to_agenda),
]

这就像一个魅力,所有以下迁移都已完成。

我的问题是,每次我运行“makemigrations”时,Django 都会再次添加迁移(= 我的问题顶部的那个)。我猜这是因为它在迁移中看不到它,因为我的代码混淆了它。

如何使用迁移来避免这种情况(不要说“这个问题出在您的数据库上,请更正您的数据库”之类的答案)?

最佳答案

Django 正在重新创建迁移,因为当您在 RunPython 操作中手动执行操作时,它无法理解添加的字段。您可以尝试的是(我自己还没有尝试过),将 AddField 操作子类化以创建自定义 AddField 操作,您可以在其中处理异常。像下面这样的东西可以工作:

from django.db import migrations, models, ProgrammingError


class AddFieldIfNotExists(migrations.AddField):

def database_forwards(self, app_label, schema_editor, from_state, to_state):
try:
super().database_forwards(app_label, schema_editor, from_state,
to_state)
except ProgrammingError as e: # sometimes it can exist
if "already exists" not in str(e):
raise


class Migration(migrations.Migration):
atomic = False
dependencies = [
('app', '0070_auto_20191023_1203'),
]

operations = [
AddFieldIfNotExists(
model_name='agenda',
name='theme',
field=models.PositiveIntegerField(default=1),
),
]

关于django - 如何忽略特定的迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com