【问题标题】:Django migration: `AlterUniqueTogether` fails with `constraint does not exist` but I think it's there [duplicate]Django迁移:`AlterUniqueTogether`因`约束不存在`而失败,但我认为它在那里[重复]
【发布时间】:2021-07-08 10:05:07
【问题描述】:

我正在尝试使用 Django 2.2 运行以下迁移:

class Migration(migrations.Migration):

    dependencies = [
        ('actstream', '0002_remove_action_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='follow',
            name='flag',
            field=models.CharField(blank=True, db_index=True, default='', max_length=255),
        ),
        migrations.AlterUniqueTogether(
            name='follow',
            unique_together=set([('user', 'content_type', 'object_id', 'flag')]),
        ),
    ]

添加迁移的 git commit 之前模型有以下约束:

unique_together = ('user', 'content_type', 'object_id')

在添加迁移的 git commit 之后:

unique_together = ('user', 'content_type', 'object_id', 'flag')

(flag 是一个新字段,它也被添加到unique_together 约束中)。

当我尝试应用迁移时,我收到以下错误消息:

psycopg2.errors.UndefinedObject: constraint "actstream_follow_user_id_content_type_id_object_id" of relation "actstream_follow" does not exist

检查我的数据库,因为它是没有迁移,但是,我看到以下内容:

我错过了什么?

谢谢!

【问题讨论】:

    标签: django


    【解决方案1】:

    似乎与此重复:

    Django unable to migrate PostgreSQL: constraint X of relation Y does not exist

    问题原来是我使用工具 pgloader 将数据库从 MySQL 转换为 PostgreSQL,并且该工具通过在 PostgreSQL 中将它们创建为索引来转换约束,而 Django PG 后端将它们创建为约束。因此,当迁移运行时,它只查找约束并没有找到任何约束。

    我通过删除索引并将其重新创建为真正的约束来解决此问题:

    drop index actstream_follow_user_id_content_type_id_object_id;
    alter table actstream_follow add constraint actstream_follow_user_id_content_type_id_object_id unique(user_id, content_type_id, object_id);
    

    【讨论】:

    • 如果您觉得它是重复的,那么您为什么要在这里复制它?只需将您的问题标记为重复...
    • 对不起,我不知道这是一个选项。现在可以了。
    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 2017-04-09
    • 1970-01-01
    • 2021-09-07
    • 2016-01-01
    • 2016-11-22
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多