Django: loaddata not working
Asked Answered
B

4

8

I generated a fixture:

python manage.py dumpdata --all > ./mydump.json

I emptied all my databases using:

python manage.py sqlflush | psql mydatabase -U mydbuser

But when i try to use loaddata:

python manage.py loaddata ./mydump.json

I'm recieving this error:

IntegrityError: Could not load tastypie.ApiKey(pk=1): duplicate key 
value violates unique constraint "tastypie_apikey_user_id_key" 
DETAIL:  Key (user_id)=(2) already exists.

I'm having this problem on production and i'm out of ideas. Someone had a similar problem?

Benbena answered 9/2, 2014 at 2:41 Comment(1)
I modified my answer to point out the fact that you need to make sure that django is stopped before trying to load in the new data. i.e. if you are running a webserver with django in the stack, make sure to stop that webserver.Signesignet
B
3

Jeff Sheffield's solution is correct, but now I find that a solution like django-dbbackup is by far the most generic and simplier way to do it with any database.

python manage.py dbbackup
Benbena answered 4/4, 2014 at 4:12 Comment(0)
I
12

Run loaddata with all @recievers commented out because they will be fired when loaddata loads your data. If @recievers create other objects as a sideeffect it will cause collisions.

Isochronous answered 28/2, 2020 at 20:50 Comment(2)
This actually helped, so genius.Ailey
Was getting a very opaque error message. This solved the problem.Chondro
S
7

First: I believe your unix pipe is incorrectly written.

# 1: Dump your json
$ python manage.py dumpdata --all > ./mydump.json

# 2: dump your schema
$ python manage.py sqlflush > schema.sql

# 3: launch psql
# this is how I launch psql ( seems to be more portable between rhel/ubuntu )
# you might use a bit different technique, and that is ok.

Edited: (very important) Make sure you do not have any active django connections running on your server. Then:

$ sudo -u myuser psql mydatabase

# 4: read in schema
mydatabase=# \i schema.sql
mydatabase=# ctrl-d

# 5: load back in your fixture. 
$ python manage.py loaddata ./mydump.json

Second: If your pipe is ok.. and it might be. Depending on your schema/data you may need to use natural-keys.

# 1: Dump your json using ( -n ) natural keys.
$ python manage.py dumpdata -n --all > ./mydump.json

# followed by steps 2-5 above.
Signesignet answered 10/2, 2014 at 6:51 Comment(0)
B
3

Jeff Sheffield's solution is correct, but now I find that a solution like django-dbbackup is by far the most generic and simplier way to do it with any database.

python manage.py dbbackup
Benbena answered 4/4, 2014 at 4:12 Comment(0)
T
-1

in my case the database was somehow used by other services so i tries to shut them all and rerun the loaddata or you can simply reboot your machine .

Tereus answered 19/12, 2023 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.