Django Backup/Restore Data

If you are using postgres, you can use pg_dump, or if using mysql, you can use mysqldump to backup your data in SQL format. Django provides another method of backing up your data, and will output in json by default, but you can also choose from xml or yaml data formats as well. The dumpdata and loaddata commands are part of the in the root of your django app.

Django's dumpdata

When called with no arguments, all json will be dumped to console.

./ dumpdata

Redirect data to a file.

./ dumpdata > /path/to/data-mysite_com-20150502.json

Redirect data to a file and compress

./ dumpdata | gzip -9 > /path/to/data-mysite_com-20150502.json.gz

Backup only a specific app's data.

./ dumpdata django_comments | gzip -9 > /path/to/data-mysite_com-django_comments-20150502.json.gz

Backup only a specific table.

./ dumpdata django_comments.comment | gzip -9 > /path/to/data-mysite_com-django_comments_comment-20150502.json.gz

By default the json output is minified and on a single line. If you would like the outputted file formatted, you can specify an indent (typically 2 or 4 spaces).

./ dumpdata --indent 2 > /path/to/data-mysite_com-20150502.json

Backup to XML (also using the formatting from above)

./ dumpdata --indent 2 --format xml > /path/to/data-mysite_com-20150502.xml

Backup to yaml (also using the formatting from above)

./ dumpdata --indent 2 --format yaml > /path/to/data-mysite_com-20150502.yml

Take A Complete Backup

When we backup django with dumpdata, we typically do not want to keep the auth.permission or contenttype tables. Though it typically makes more sense to backup using the native db tools in a production enviornment. These json backups are useful to quickly seed the data in a dev or qa environment.

./ dumpdata --exclude contenttypes --exclude auth.permission > /path/to/backup/mysite_com.json

Django loaddata

We can restore the JSON, XML or YAML created above with loaddata. This will only work on a fresh database, if a primary key already exists in a table, it will be unable to make the insert and error out.

./ loaddata /path/to/data-mysite_com-20150502.json