Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?

Change Django database backend in existing projects

Django Dec 26, 2020

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).

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


Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.