Change Django database backend in existing projects

Change Django database backend in existing projects

When reading about Django deployments we usually talk about scaling. But we mean scaling up.

What if you plan for your app to be super successful and it ends up to be .... just successful? Maybe you overestimated your database needs and after all, you need something smaller.

Django takes care of how to talk to the various database backends. So you can switch database backends with just a few line changes. But you need to migrate your data from the current database to the new database.

If you haven't touched the database directly (i.e. all the interactions with your current database were done via Django models), then migrating your database is quite easy.

Export data

Use Django's dumpdata to export all your database data into a file. The command is quite customizable (e.g. you can choose serialization format), but the JSON default with a reasonable indent makes it human-readable in case you need to debug something.

Note that it can take some time to complete, depending on the amount of data store in your DB.

python dumpdata --natural-foreign --natural-primary --indent 2 > /path/to/datadump.json

In case you run into UNIQUE constraint failed errors, you can try excluding the auth.Permissions and contenttypes tables.

python dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 2 > /path/to/datadump.json

Prepare DB

Before importing your dump, switch the DB backend in, and recreate all the tables.

python migrate --run-syncdb

Import data

Finally, import all the data from the dump file.

 python loaddata /path/to/datadump.json

A common issue is for your models to have decorators (e.g. @receiver) that run after saving models that break when triggered from the loaddata command. If this is the case, disable/comment those decorators before running the command (and don't forget to enable/uncomment when done).

Do you enjoy what you are reading? Subscribe to our non-annoying-once-a-month digest :)

Hopefully, you can migrate your DB without any issues quickly and easily. Happy coding!

Show Comments