Django tip: Transfering data from Sqlite to other databases (MySQL, PostgreSQL, etc)

/ #Django


In this short little guide you will learn how to export data from your local Sqlite database and import it in a new one.

Many developers, including my self, like to use the built in Sqlite database when we create new Django projects locally.

Sqlite isn't really suited for using in production (at least not if you have many create and update requests). So in production, we tend to use databases like MySQL or PostgreSQL.

Since we often start out with Sqlite, we also add a lot of data we want to export and import to the new databases on the live server as well.

Exporting

To export the data, we only need to run one command:

$ python manage.py dumpdata > db-dump.json

This command will now give us a new file called "db-dump.json" with all of the data and information from Sqlite.

The steps between

There are a few steps you need to follow now before we can import this to the new database

First, update your "settings.py" file. Remove the information about Sqlite, and insert the correct information so you can connect to your new database.

After that, we can update the database models by running:

$ python manage.py migrate

All of the tables should now be created in your new database. But we need to go into the shell and remove something called ContentType.

$ python manage.py shell

When you have the shell running, type these two commands the delete the necessary ContentTypes:

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.all().delete()

Importing

The last step now is to import the "db-dump.json" file to our new database.

$ python manage.py loaddata db.json

And then you're done :-)

Comments

Kaddour | Nov 12, 21 11:59

In the last command line file should be `db-dump.json` or ` db.json` ?

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.