Django
Blog for Poems in Django Part IV

Blog for Poems in Django Part IV

In this blog post we will learn to migrate Django project from SQLite database to PostgreSQL.

Table of contents.

Install PostgreSQL on ubuntu

#terminal
sudo apt-get update
sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql.service

Using PostgreSQL to create user and database

#terminal
sudo -i -u postgres
psql
postgres=# CREATE USER blog WITH PASSWORD 'xxxxx';
postgres=# CREATE DATABASE blog OWNER blog ENCODING 'UTF8';

After completing the database you can check it by:

#terminal
postgres=# \l

Click q to exit.

Dumping the existing data

Before switching the database in the Django project, we need to dump the existing data from the SQLite database. We will export the data, switch the project’s database to PostgreSQL, and import the data into the new database.

#terminal
python manage.py dumpdata --indent=2 --output=mysite_data.json

Switching the database in the project

Edit the settings.py file of your project and modify the DATABASES setting to make it look as follows.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'blog',
        'USER':'blog',
        'PASSWORD':'xxxxx',
        'HOST': 'localhost',
        'PORT': '',

    }
}

Now, migrate with the following command.

#Terminal
python manage.py migrate

Loading the data into the new database

Run the following command to load the data into the PostgreSQL databasel

python manage loaddata mysite_data.json

Run the server. Now your Django is running on PostgreSQL.