Django:loaddata不工作

2024-04-29 11:03:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我生成了一个fixture:

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

我清空了所有数据库,使用:

python manage.py sqlflush | psql mydatabase -U mydbuser

但当我尝试使用loaddata时:

python manage.py loaddata ./mydump.json

我收到这个错误:

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.

我在生产上遇到了这个问题,我没有主意了。有人有类似的问题吗?


Tags: keypyid数据库jsonmanagealltastypie
2条回答

Jeff Sheffield的解决方案是正确的,但是现在我发现像django-dbbackup这样的解决方案是迄今为止对任何数据库进行处理的最通用、最简单的方法。

python manage.py dbbackup

首先: 我相信你的unix管道写错了。

# 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.

编辑:(非常重要) 确保您的服务器上没有运行任何活动的django连接。然后:

$ 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

秒: 如果你的烟斗没问题。。可能是的。根据您的模式/数据,您可能需要使用自然键。

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

# followed by steps 2-5 above.

相关问题 更多 >