How to migrating the database engine for Django

In this article I'll run you through how to migrate from one data storage solution to another.

  • 14 Oct 2013
  • Matthew Wittering

Depending upon the projects you're operating, it's conceivable that you'll at some stage need to migrate between two infrastructures, and possibly the underlying software stack. Conceivably this may include for example the depreciation of MySQL in favour of PostgreSQL.

Recently, in light of some malicious vandalism, I chose to migrate from MySQL to SQLite. You'll likely find this a strange decision, and you're probably right. However I found phpMyAdmin to be the weak link my VPS, and after launching a new instance decided, not to reinstall the program. Instead I decided to keep my software and technical footprint to a bare minimum and installed SQLite in conjunction with Django. In my case, I think SQLite is very appropriate for small websites and blogs.

This decision did however promote a small about important technical issues to work through. How do I get my data out of MySQL and into SQLite, or any other database solution for that matter. Fortunately, Django has some nifty management commands to solve this conundrum.

Step 1 - Find manage.py

Start by firing up a terminal window and change your working directory for the one which contains manage.py. Now run this command.

python manage.py dumpdata > database.json

Step 2 - Create a new database

Modify the database configuration in settings.py. Then run the following command to configure the new database with your models and default settings.

python manage.py syncdb

Step 3 - Empty the new database

Now run either of these commands to empty the database ready to import your data.json.

python manage.py sqlflush

or

python manage.py sqlflush | log into MySQL, PostgreSQL, MSSQL or Oracle

Step 4 - Import the JSON file

Now, all that remains is to load the JSON file into memory with manage.py and Django ensure all your data is imported and stored correctly. I've read, by completing the migration using these steps, you should ensure that no advanced database specific features are lost.

python manage.py loaddata database.json

And, there you have it. You are good to go!