【发布时间】:2017-01-16 16:45:04
【问题描述】:
这是我的 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])
在尝试删除所有测试用户或其中任何一个用户后,我收到以下错误。
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".
级联删除默认为真,为什么我会收到这个,我该如何解决?我正在使用 PostgreSQL + Django 1.8
编辑:小前提条件:我已将 primary_key 从默认更改为 fb_id。并且有重复,因为它没有被设置为唯一的。因此,当我尝试 migrate/makemigrations/syncdb 时会引发此错误:
django.db.utils.IntegrityError: could not create unique index "blog_userprofile_fb_id_ce4e6e3086081d4_uniq"
DETAIL: Key (fb_id)=(0) is duplicated.
这就是我尝试删除所有测试用户的原因
当我尝试重置所有内容时,我尝试恢复默认主键,我收到:
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "blog_userprofile"
【问题讨论】:
-
您为什么使用该物业?只需给
OneToOneField一个related_name! -
@schwobaseggl 它被 ForeignKey 引用,但只有默认值(没有选项)
-
@schwobaseggl 为什么?跟随错误的教程,可能没有认真阅读文档
-
我确实看到它会创建配置文件,如果不存在并且不会引发异常,但正如 Python 的 ZEN 所说:“显式优于隐式”;-)
-
这看起来好像自动创建的中间模型上的“来自”
ForeignKey是on_delete=models.PROTECT,这很奇怪,因为自动创建的模型上的这些字段是硬编码的CASCADE。你确定你的模型和你的数据库是同步的吗?
标签: python django postgresql