Django loaddata UNIQUE constraint failed
json, loaddata, python, unique
Solution
Exclude ContentType and Auth Permissions objects when creating a db dump.
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
Problem
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: ``` 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? If relevant, `UserProfile` just extends the default `User` model with a `OneToOneField` relation, as proposed here. Here is what `mydata.json` contains: ``` [ { "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,