Django使用manage.py备份与恢复数据

Django dumpdata and loaddata

dumpdata command

  • It is a django management command, which can be use to backup(export) you model instances or whole database

dumpdata for basic database dump

  • Following command will dump whole database in to a db.json file
./manage.py dumpdata > db.json

dumpdata for backup specific app

  • Following command will dump the content in django admin app into admin.json file
./manage.py dumpdata admin > admin.json

dumpdata for backup specific table

  • Following command will dump only the content in django admin.logentry table
./manage.py dumpdata admin.logentry > logentry.json
  • Following command will dump the content in django auth.user table
./manage.py dumpdata auth.user > user.json

dumpdata (--exclude)

  • You can use --exclude option to specify apps/tables which don't need being dumped

  • Following command will dump the whole database with out including auth.permission table content

./manage.py dumpdata --exclude auth.permission > db.json

dumpdata (--indent)

  • By default, dumpdata will output all data on a single line. It isn’t easy for humans to read

  • You can use the --indent option to pretty-print the output with a number of indentation spaces

./manage.py dumpdata auth.user --indent 2 > user.json
  • Example output of above command is below

Picture

dumpdata (--format)

  • By default, dumpdata will format its output in JSON

  • You can specify the format using --format option

  • Command supports for following formats(serialization formats)

  1. json
  2. xml
  3. yaml
./manage.py dumpdata auth.user --indent 2 --format xml > user.xml
  • Above command output an xml file(user.xml)

Picture

loaddata command

  • This command can be use to load the fixtures(database dumps) into database
./manage.py loaddata user.json
  • This command will add the user.json file content into the database

Restore fresh database

  • When you backup whole database by using dumpdata command, it will backup all the database tables

  • If you use this database dump to load the fresh database(in another django project), it can be causes IntegrityError (If you loaddata in same database it works fine)

  • To fix this problem, make sure to backup the database by excluding contenttypes and auth.permissions tables

./manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
  • Now you can use loaddata command with a fresh database
./manage.py loaddata db.json

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值