8

我生成了一个夹具:

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.

我在生产中遇到了这个问题,我没有想法。有人有类似的问题吗?

4

3 回答 3

11

loaddata在所有@recievers 注释掉的情况下运行,因为它们会在loaddata加载数据时被触发。如果@recievers 创建其他对象作为副作用,它将导致冲突。

于 2020-02-28T20:50:35.200 回答
7

第一: 我相信你的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.
于 2014-02-10T06:51:19.897 回答
3

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

python manage.py dbbackup
于 2014-04-04T04:12:08.493 回答