【问题标题】:IntegrityError when loading Django fixtures with OneToOneField using SQLite使用 SQLite 使用 OneToOneField 加载 Django 固定装置时出现 IntegrityError
【发布时间】: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 已加载。

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

【问题讨论】:

    标签: django sqlite


    【解决方案1】:

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

    【讨论】:

    • 您是指第一次加载数据时还是从一个架构移动到另一个架构时?
    • 它来自 Django 文档docs.djangoproject.com/en/1.7/howto/initial-data:“自动加载初始数据fixtures 1.7 版后不推荐使用:如果应用程序使用迁移,则不会自动加载fixtures。因为Django 中的应用程序需要迁移2.0,此行为被视为已弃用。如果您想为应用加载初始数据,请考虑在数据迁移中进行。"
    猜你喜欢
    • 1970-01-01
    • 2013-09-02
    • 2016-04-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多