DEV Community

RockAndNull
RockAndNull

Posted on • Originally published at rockandnull.com on

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 manage.py dumpdata --natural-foreign --natural-primary --indent 2 > /path/to/datadump.json
Enter fullscreen mode Exit fullscreen mode

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

python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 2 > /path/to/datadump.json
Enter fullscreen mode Exit fullscreen mode

Prepare DB

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

python manage.py migrate --run-syncdb
Enter fullscreen mode Exit fullscreen mode

Import data

Finally, import all the data from the dump file.

 python manage.py loaddata /path/to/datadump.json
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)