简体   繁体   English

Django loaddata UNIQUE 约束失败

[英]Django loaddata UNIQUE constraint failed

I'm running python manage.py loaddata 'path/to/mydata.json' with an empty database ( User and UserProfile tables are created but not populated), however, I'm getting the following error:我正在使用空数据库运行python manage.py loaddata 'path/to/mydata.json' (创建了UserUserProfile表但未填充),但是,我收到以下错误:

django.db.utils.IntegrityError: Problem installing fixture 'path/to/mydata.json': Could not load myapp.UserProfile(pk=1): UNIQUE constraint failed: myapp_userprofile.user_id

I checked (even after running this command) and the database is not populated at all.我检查了(即使在运行此命令之后)并且根本没有填充数据库。 So how can it be giving an error that the pk is not unique?那么如何给出 pk 不是唯一的错误呢?

If relevant, UserProfile just extends the default User model with a OneToOneField relation, as proposed here .如果相关, UserProfile只是使用OneToOneField关系扩展默认User模型,如此处建议那样。

Here is what mydata.json contains:这是mydata.json包含的内容:

[
    {
        "model": "auth.user",
        "pk": 1,
        "fields": {
            "password": "pbkdf2_sha256..",
            "last_login": "2016-10-22T15:19:46.926Z",
            "is_superuser": true,
            "username": "thesuperuser",
            "first_name": "",
            "last_name": "",
            "email": "a@a.co",
            "is_staff": true,
            "is_active": true,
            "date_joined": "2016-10-22T14:48:27.394Z",
            "groups": [],
            "user_permissions": []
        }
    },
    {
        "model": "auth.user",
        "pk": 2,
        "fields": {
            "password": "pbkdf2_sha256..",
            "last_login": null,
            "is_superuser": false,
            "username": "user1",
            "first_name": "User",
            "last_name": "One",
            "email": "",
            "is_staff": false,
            "is_active": true,
            "date_joined": "2016-10-22T15:20:32Z",
            "groups": [],
            "user_permissions": []
        }
    },
    {
        "model": "auth.user",
        "pk": 4,
        "fields": {
            "password": "pbkdf2_sha256..",
            "last_login": null,
            "is_superuser": false,
            "username": "user3",
            "first_name": "User",
            "last_name": "Three",
            "email": "",
            "is_staff": false,
            "is_active": true,
            "date_joined": "2016-10-22T15:21:09Z",
            "groups": [],
            "user_permissions": []
        }
    },
    {
        "model": "auth.user",
        "pk": 3,
        "fields": {
            "password": "pbkdf2_sha256..",
            "last_login": null,
            "is_superuser": false,
            "username": "user2",
            "first_name": "User",
            "last_name": "Two",
            "email": "",
            "is_staff": false,
            "is_active": true,
            "date_joined": "2016-10-22T15:21:03Z",
            "groups": [],
            "user_permissions": []
        }
    },
    {
        "model": "myapp.userprofile",
        "pk": 1,
        "fields": {
            "user": 1,
            "money": 100
        }
    },
    {
        "model": "myapp.userprofile",
        "pk": 2,
        "fields": {
            "user": 2,
            "money": 100
        }
    },
    {
        "model": "myapp.userprofile",
        "pk": 3,
        "fields": {
            "user": 3,
            "money": 100
        }
    },
    {
        "model": "myapp.userprofile",
        "pk": 4,
        "fields": {
            "user": 4,
            "money": 100
        }
    }
]

Thanks for any help,谢谢你的帮助,

Exclude ContentType and Auth Permissions objects when creating a db dump.创建数据库转储时排除 ContentType 和 Auth Permissions 对象。

python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 2 > dump.json

After that you should be able to run the command without any issue之后,您应该能够毫无问题地运行该命令

python manage.py loaddata dump.json

Credit to https://www.coderedcorp.com/blog/how-to-dump-your-django-database-and-load-it-into-/ for saving my day感谢https://www.coderedcorp.com/blog/how-to-dump-your-django-database-and-load-it-into-/为我节省了一天

Today ( 24th, April, 2020 ) I had a similar problem with Django 2.2今天( 2020 年 4 月 24 日)我在Django 2.2上遇到了类似的问题

My fixtures file was as simple as this:我的夹具文件就像这样简单:

[
{
    "model": "contenttypes.contenttype",
    "pk": 1,
    "fields": {
        "app_label": "admin",
        "model": "logentry"
    }
},
{
    "model": "contenttypes.contenttype",
    "pk": 2,
    "fields": {
        "app_label": "auth",
        "model": "permission"
    }
}]

When I ran ./manage.py loaddata initial_data.json , I got:当我运行./manage.py loaddata initial_data.json时,我得到:

django.db.utils.IntegrityError: Problem installing fixture '/home/user/reponame/projectname/initial_data.json': Could not load contenttypes.ContentType(pk=2): UNIQUE constraint failed: django_content_type.app_label, django_content_type.model

What I did to make it work was just rename the pk to id for the contenttypes.contenttype model.我所做的只是将pk重命名为contenttypes.contenttype模型的id After that, the migration worked as expected.之后,迁移按预期工作。

./manage.py loaddata initial_data.json 
Installed 2 object(s) from 1 fixture(s)

After the change, my initial_data.json file was:更改后,我的initial_data.json文件为:

[
{
    "model": "contenttypes.contenttype",
    "id": 1,
    "fields": {
        "app_label": "admin",
        "model": "logentry"
    }
},
{
    "model": "contenttypes.contenttype",
    "id": 2,
    "fields": {
        "app_label": "auth",
        "model": "permission"
    }
}]

It is worth mentioning that my original initial_dataj.json has many other models, but renaming pk to id only for the contenttypes.contenttype solved my problem.值得一提的是,我原来的initial_dataj.json还有很多其他的模型,但是将pk重命名为id只为contenttypes.contenttype解决了我的问题。

I had a similar problem.我有一个类似的问题。 Inspired by this post:受这篇文章的启发:

https://github.com/yourlabs/django-cities-light/issues/89 (See 'how to fix it') https://github.com/yourlabs/django-cities-light/issues/89 (请参阅“如何修复它”)

before running the loaddata command, I commented the receiver signal decorator before the 'saving function', and it worked.在运行 loaddata 命令之前,我在“保存功能”之前注释了接收器信号装饰器,它起作用了。

转到json文件并将evey单个'pk'更改为'id'如果你使用vs代码你可以选择1并按cmd/ctrl + f2作为快捷方式

Had the same problem while exporting and importing a model with a ManyToMany relation.在导出和导入具有多对多关系的模型时遇到了同样的问题。 This was, because I manually speficied the ManyToMany through model while exporting, what caused an unique constraint error.这是因为我在导出时手动指定了 ManyToMany through 模型,导致了唯一约束错误。

class MyModel(model.Model):
    
    groups = models.ManyToManyField(
        'myapp.mymodel',        
        
    )

You only need to execute dumpdata myapp.mymodel , not `dumpdata myapp.mymodel myapp.mymodel_groups"您只需要执行dumpdata myapp.mymodel ,而不是 `dumpdata myapp.mymodel myapp.mymodel_groups"

Otherwise, your through model data is in the export twice, and causes a unique constraint error.否则,您的直通模型数据在导出中两次,并导致唯一约束错误。

It`sa good question how this behaves, when you specify an explicit through model...i don't know and have no time to test :)这是一个很好的问题,当你指定一个明确的模型时,它的行为如何......我不知道也没有时间测试:)

在加载夹具时注释您的信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM