完整性错误:更新或删除违反外键约束.Django + PosrgeSQL

7 python django postgresql

这是我的UserProfile修改

 class UserProfile(models.Model):
        user = models.OneToOneField(User)
        fb_id = models.IntegerField(primary_key=True,null=False,blank=True)
        follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False)
    User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Run Code Online (Sandbox Code Playgroud)

尝试删除所有测试用户或其中任何一个用户后,我收到以下错误.

    django.db.utils.IntegrityError: update or delete on table "blog_userprofile" violates foreign key constraint "blog_from_userprofile_id_a482ff43f3cdedf_fk_blog_userprofile_id" on table "blog_userprofile_follows"
DETAIL:  Key (id)=(4) is still referenced from table "blog_userprofile_follows".
Run Code Online (Sandbox Code Playgroud)

默认情况下级联删除应该是真的,为什么我收到这个,我该如何解决?我正在使用PostgreSQL + Django 1.8

编辑:小先决条件:我primary_key从默认更改为fb_id.并且有重复,因为它没有设置唯一.因此,当我尝试迁移/ makemigrations/syncdb时会引发此错误:

   django.db.utils.IntegrityError: could not create unique index "blog_userprofile_fb_id_ce4e6e3086081d4_uniq"
DETAIL:  Key (fb_id)=(0) is duplicated.
Run Code Online (Sandbox Code Playgroud)

这就是我试图删除所有测试用户的原因

当我尝试重置所有内容时,我试图恢复默认主键,我收到:

django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "blog_userprofile"
Run Code Online (Sandbox Code Playgroud)

小智 4

经过多次测试,我发现我的约束没有分配 Deferrable 和 Deferred 选项,因为我当前的数据库 PostgreSQL 是从 MySQL 迁移的。然后我在数据库上手动分配此选项并开始工作。

在此输入图像描述

有关此选项的更多信息,请访问以下链接: PostgreSQL 中的可延迟检查约束

我希望这能有所帮助。