Django管理员“重复的键值违反了唯一约束".密钥(user_id)=(1)已存在 [英] Django admin "duplicate key value violates unique constraint" Key (user_id)=(1) already exists
问题描述
仅当我尝试通过django管理站点更新任何内容时,这才发生在我身上.否则我没有问题.我收到的错误是:
This is only happening to me when I try to update anything via the django admin site. Otherwise I have no problems. The error I am getting is:
IntegrityError at /admin/ledger/user/1/
duplicate key value violates unique constraint "ledger_googleprofile_user_id_key"
DETAIL: Key (user_id)=(1) already exists.
这是我的Google个人资料模型的样子:
Here is what my google profile model looks like:
#ledger.models
class GoogleProfile(models.Model):
plus_id = models.CharField(max_length=2000, null=True, blank=True)
info = JSONField(null=True, blank=True)
youtube_info = JSONField(null=True, blank=True)
user = models.ForeignKey('User', related_name='google_profile', blank=True, null=True)
我尝试运行 python manage.py sqlsequencereset分类帐
,然后将其粘贴到psql中,但这不能解决问题.这很奇怪,因为即使没有与之关联的GoogleProfile的用户在尝试保存到管理员时仍然会抛出此错误.
I've tried running python manage.py sqlsequencereset ledger
and then pasting that into psql, but that isn't solving the problem. It's weird because even users that don't have a GoogleProfile associated with them still throw this error when trying to save in the admin.
关于可能出现问题的任何想法.我宁愿不必删除生产数据库并重新开始...
Any ideas on what the problem could be. I would rather not have to delete my production database and start over...
写完这个之后,我认为问题可能是因为 GoogleProfile.user
字段以前可能是 oneToOne
.我不是很肯定,但是我认为这是一个oneToOne,我更改为ForeignKey(许多更改为一个),这可以解释为什么存在唯一约束的问题.但是运行 manage.py makemigrations并进行迁移
是否可以解决问题?知道如何手动解决此问题吗?
After writing this out I think the problem might be because the GoogleProfile.user
field may have been a oneToOne
before. I am not positive but I think it was a oneToOne that I changed to a ForeignKey (many to one) which would explain why there are problems with a unique constraint. But should running manage.py makemigrations and migrate
solve the problem? Any idea how to solve this manually?
推荐答案
要手动删除约束,请运行以下命令仔细检查约束名称:
To remove the constraint manually, run the following to double check the constraint name:
SELECT *
FROM information_schema.constraint_table_usage
WHERE table_name = 'ledger_googleprofile';
然后
ALTER TABLE ledger_googleprofile DROP CONSTRAINT constraint_name;
鉴于您发布的错误,我猜实际的SQL如下,但是我会运行SELECT查询只是为了仔细检查:
Given the error you've posted I'd guess the actual SQL is that below, but I'd run the SELECT query just to double check:
ALTER TABLE ledger_googleprofile DROP CONSTRAINT ledger_googleprofile_user_id_key;
这篇关于Django管理员“重复的键值违反了唯一约束".密钥(user_id)=(1)已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!