Django `loaddata` and `dumpdata` examples


Many times we need to load data into django database from other environment. Most raw method is to do database export and import however you need to have required database skillset to do this operation. Also, while doing this database export and import, you might run into DBA related issues. You need to know how to manage database at some good extend, however if you are using django, you have very nice utilities loaddata and dumpdata. These are django management command, which can be use to backup(export) you model instances or whole database.

loaddata

This command has following options

python3 manage.py dumpdata [app_label].[ModelName] --format [json][xml] --exclude auth.permission --indent 4 

If no application name is provided, all installed applications will be dumped.

Take backup of whole database

python3 manage.py dumpdata > db.json

Take backup of specific Application

python3 manage.py dumpdata blog > blog-db.json

Take backup of specific table / model from specific application

python3 manage.py dumpdata blog.posts > blog-posts-db.json

If you want to dump data in different format, you can do so by passing required parameter

 python3 manage.py dumpdata --format xml > db.xml

If you want to avoid integrrity errors, dumpdata by exlcuding following

python3 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json

To make it human readable

python3 manage.py dumpdata --indent 4 > db.json 

loaddata

The output of dumpdata can be used as input for loaddata.

python3 manage.py loaddata db.json

If you have exported only specific table and now you want to load specific table, you can do some by running same command. It will load only table for which data is present in the file. All other tables remains as is.

python3 manage.py loaddata blog-posts-db.json

post by Pravin

#django

Comments