【发布时间】:2014-10-21 13:10:26
【问题描述】:
当尝试通过syncdb 命令加载初始数据时,Django 抛出以下错误:
django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'user_profile_userprofile' with primary key '1' has an invalid foreign key: user_profile_userprofile.user_id contains a value '1' that does not have a corresponding value in user_customuser.id.
UserProfile 模型和 CustomUser 之间存在 OneToOne 关系:
class UserProfile(TimeStampedModel):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
运行 ./manage.py dumpdata user --format=json --indent=4 --natural-foreign 会产生以下结果:
自定义用户模型数据
[
{
"fields": {
"first_name": "Test",
"last_name": "Test",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2014-10-21T11:33:42Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$12000$Wqd4ekGdmySy$Vzd/tIFIoSABP9J0GyDRwCgVh5+Zafn9lOiTGin9/+8=",
"email": "test@test.com",
"date_joined": "2014-10-21T11:22:58Z"
},
"model": "user.customuser",
"pk": 1
}
]
运行 ./manage.py dumpdata user_profile --format=json --indent=4 --natural-foreign 会产生以下结果:
个人资料模型
[
{
"fields": {
"weight": 75.0,
"created": "2014-10-21T11:23:35.536Z",
"modified": "2014-10-21T11:23:35.560Z",
"height": 175,
"user": 1,
},
"model": "user_profile.userprofile",
"pk": 1
}
]
仅加载 CustomUser 模型的初始数据,然后通过加载数据跟进 UserProfile 效果很好,这表明 syncdb 正在尝试加载 CustomUser 之前的 UserProfile 已加载。
如果最简单的解决方案是强制加载顺序,那么最简单的方法是什么?
【问题讨论】: