Switching To PostgreSQL For Your Django Project


The default database option for Django is SQLite, which is a great option to get up and running quickly but it may not scale well beyond a certain point. A good alternative is PostgreSQL and, although it's overkill for my purposes, it's what I'm using for this website.

Follow the steps below to start using PostgreSQL for your Django project. If you are working with an existing project you will need to backup the data in your current database beforehand and restore it in PostgreSQL afterwards.

Install Required Packages

Open the terminal and run the commands below to install the necessary packages.

libpq allows client programs to communicate with a PostgreSQL database.

sudo apt-get install libpq-dev

python3-dev is required to build psycopg2. Note: replace python3-dev with python-dev if you are using Python 2.

sudo apt-get install python3-dev

psycopg2 is a popular PostgreSQL database adapter for Python.

sudo apt-get install python-psycopg2

Finally install PostgreSQL itself.

sudo apt-get install postgresql postgresql-contrib

Set Up PostgreSQL

Create the database user to be used in your Django project. Replace dbuser with your desired username.

sudo -u postgres createuser --superuser dbuser

Open psql, a terminal-based front-end to PostgreSQL, and set the password for the database user just created. Note: replace dbuser with the username you chose in the previous step.

sudo -u postgres psql
\password dbuser

Give the database user permission to create databases. You will run into errors when trying to run Django tests if you do not give the database user this permission. Note: replace dbuser with the username you chose earlier.


Lastly, exit psql and create the database for your Django project. You will also need to create a database that matches the name of your database user otherwise you will receive an error when attempting to open the psql prompt normally (i.e., when running the psql command from the terminal). Note: Replace djangoproject with your desired database name and dbuser with the username you chose earlier.

createdb djangoproject
createdb dbuser

Update Your Django Project

Install the Python package for psycopg2.

pip install psycopg2

Update your Django project's settings.py file. At a minimum you will need to update the DATABASES dictionary with the settings below. See Keep Sensitive Data Out Of Source Control for a way to store this information more securely. Note: replace djangoproject, dbuser, and dbpassword with the information you chose in the previous section.

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': 'dbuser',
        'PASSWORD': 'dbpassword',

Sync the new database by running the command below from the terminal in the same directory as your project's manage.py file.

python manage.py migrate

Note: This post was written using Ubuntu 14.04

View other posts