gpt4 book ai didi

python - 在 Django 装置中加载 auth.user 和配置文件模型时出现 IntegrityError

转载 作者:行者123 更新时间:2023-11-28 22:56:23 24 4
gpt4 key购买 nike

我正在尝试创建一些固定装置以用于在 Django 中运行测试。现在,我只是从我的开发数据库中转储适当的模型,然后通过测试加载它们。这是我用来转储灯具的命令:

python manage.py dumpdata accounts.Profile auth.User -n auth.User --indent 4 -e contenttypes > path/to/fixture.json

正在关注 this questionthis one我添加了使用自然键和排除内容类型的标志。这没有帮助——我收到此错误消息:

IntegrityError: Could not load accounts.Profile(pk=1): duplicate key value violates unique constraint "accounts_profile_user_id_key"
DETAIL: Key (user_id)=(1) already exists

我已经手动检查了 fixture ,但该用户 ID 只有一个条目。 Profile 模型非常标准,带有一些包含个人信息的额外字段。它通过以下链接到模型中的用户:

def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

以完整性的名义,这是固定装置的样子:

{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "unique_username",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2013-03-31T23:19:44.391",
"groups": [],
"user_permissions": [],
"password": "secret",
"email": "email",
"date_joined": "2013-03-13T21:30:39.225"
}
},
{
"pk": 1,
"model": "accounts.profile",
"fields": {
"status": "active",
"first_name": "John",
"last_name": "Smith",
"middle_name": null,
"headline": "Something very cool",
"user": [
"unique_username"
],
"location": null
}
}

有什么想法吗?是因为我用来链接用户和配置文件的钩子(Hook)吗?

我在 Mac OS X (10.7.5) 上使用 Python 2.6 的 Enthought 发行版运行 Django 1.4。

最佳答案

如果您有以下情况,OneToOneFields() 经常会发生这种情况:

Profile.user = models.OneToOneField(User) 当 django 创建用户记录时,它会自动为这些用户创建配置文件(可能通过 post_save)。因此,当 loaddata 开始导入配置文件时,每个用户已经拥有一个配置文件,并且额外的配置文件打破了约束。

我有 2 个模型通过 OneToOneField 指向用户:

  • 简介;
  • 日历。

解决问题:

1) 将 auth.user 导出到单独的 auth_user.json 中;

./manage.py dumpdata --indent=4 auth.user > auth_user.json

2)导出其他模型:

./manage.py dumpdata --indent=4 -e sessions -e admin -e contenttypes -e auth.Permission --natural-foreign > other_models.json

3)加载用户记录:./manage.py loaddata auth_user

4) 打开./manage.py shellshell_plus并删除所有个人资料和日历记录:

Profiles.objects.all().delete()
Profiles.objects.all().count()
Calendar.objects.all().delete()
Calendar.objects.all().count()

5) 加载其余记录:

./manage.py loaddata other_models

关于python - 在 Django 装置中加载 auth.user 和配置文件模型时出现 IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775888/

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