使用SQLite使用OneToOneField加载Django灯具时的IntegrityError

时间:2014-10-21 13:10:26

标签: django sqlite

尝试通过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会产生以下结果:

CustomUser模型数据

[
{
    "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

如果最简单的解决方案是强制加载顺序,最简单的方法是做什么?

1 个答案:

答案 0 :(得分:1)

我猜你应该使用Migrations https://docs.djangoproject.com/en/1.7/topics/migrations/,它们是有序的。但如果您使用较旧的Django版本然后使用1.7,请安装south https://south.readthedocs.org/en/latest/