← Back to list

Django and Databases: How to Connect Relational Databases and Which One You Should Choose

Introduction

Said Alfahulmizan in Python in Plain English · 2025-09-15 00:36 · 0 claps · 8.4 min read paywalled
#django-database #django-mysql-connection #django-postgresql-setup #postgresql #mysql
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Django and Databases: How to Connect Relational Databases and Which One You Should Choose

Image by Stephan from Pixabay

Image by Stephan from Pixabay

Introduction

Imagine building a house without a foundation. You could put up the walls, design the roof, and paint it beautifully, but the first storm would bring it all down. In web development, the database is the foundation. It’s where your application’s data lives — the users, the posts, the products, the transactions, everything.

Now, if the database is the foundation, Django is like the construction team that makes building that house easier, faster, and much less stressful. Django’s biggest strength is its Object-Relational Mapper (ORM), which allows you to interact with databases using Python code instead of writing raw SQL queries.

But here’s the challenge: Django doesn’t tie you to one specific database. You get to choose. Do you want to go with SQLite for simplicity, MySQL for familiarity, or PostgreSQL for power and scalability? The decision is yours — and it matters a lot.

In this reading, we will explore why databases are crucial in Django, the primary databases Django supports (SQLite, MySQL, PostgreSQL, and others), various methods for connecting Django to these databases, and which one is most recommended for your project.

By the end of this reading, you will not only know how to connect Django to a database but also feel confident in choosing the right one for your project.

Why Django Loves Databases

Before we dive into connections, let’s pause and appreciate how Django handles databases.

Normally, when you work with a database like MySQL or PostgreSQL, you have to write SQL queries like:

SELECT * FROM books WHERE author = "J.K. Rowling";

That’s fine if you love SQL, but for large projects, it quickly becomes messy. Django solves this by giving us the ORM (Object-Relational Mapper).

With Django, the same query looks like this:

books = Book.objects.filter(author="J.K. Rowling")

Notice how it looks like plain Python? Django automatically translates it into the correct SQL for the database you’re using. And that’s why choosing the right database is important: Django adapts to it, but the database’s strengths and weaknesses still affect your app.

The Main Database Options for Django

A. SQLite — The Default Starter

Image by CopyrightFreePictures from Pixabay

Image by CopyrightFreePictures from Pixabay

If you’ve just started a Django project without changing any settings, congratulations — you’re already using SQLite. It’s Django’s default database.

Pros:

  • Zero configuration. Works right out of the box.
  • Great for learning and small projects.
  • Lightweight (just a single file).

Cons:

  • Not great for high-traffic websites.
  • Limited features compared to PostgreSQL or MySQL.

Think of SQLite as your practice bike. It’s perfect to start with, but you wouldn’t race the Tour de France on it.

B. MySQL — The Familiar Choice

Photo by Rubaitul Azad on Unsplash

Photo by Rubaitul Azad on Unsplash

MySQL is one of the world’s most popular databases. Many developers are already comfortable with it, which makes it a natural choice.

Pros:

  • Widely supported and documented.
  • Works well for medium-to-large projects.
  • Easier to find hosting and support.

Cons:

  • Historically weaker at handling advanced features like complex queries and JSON fields (though much better now).
  • Some quirks with Django’s ORM compatibility (e.g., strict transactions).

MySQL is like the reliable family car. It gets you where you need to go, but it might lack some of the fancy features of a luxury vehicle.

C. PostgreSQL — The Django Darling

Created using Canva

Created using Canva

If Django had a “best friend” in the database world, it would be PostgreSQL.

Pros:

  • Full compatibility with all of Django’s advanced features.
  • Supports JSON fields, full-text search, GIS (geospatial data), and more.
  • Extremely stable and scalable.

Cons:

  • Slightly more complex to configure than SQLite or MySQL.
  • Hosting can sometimes be pricier than MySQL.

PostgreSQL is like a luxury car with all the bells and whistles. It might take a little more effort to learn, but once you do, you’ll wonder why you didn’t start there.

D. Others (Oracle, MariaDB, SQL Server)

Django also supports Oracle and can connect to MariaDB or SQL Server through third-party backends. These are usually chosen for enterprise reasons, but for most developers, SQLite, MySQL, or PostgreSQL will be more than enough.

How to Connect Django to Databases

A. SQLite (Default Setup)

Good news: if you’ve already started a Django project, you’ve been using SQLite without even trying. Django comes pre-configured for it.

In your project’s settings.py, you’ll see something like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / "db.sqlite3",
    }
}

That’s it. No password, no host, no extra configuration. Your database is just a file (db.sqlite3) inside your project.

When to use SQLite:

  • Learning Django.
  • Prototyping and testing.
  • Small projects with light traffic.

But when you’re ready to go beyond prototypes, it’s time to meet MySQL or PostgreSQL.

B. MySQL

To use MySQL, you first need to install a connector so Django can “talk” to it. The most common one ismysqlclient, and this is the most recommended one because it is native and provides performance optimization within the Django ecosystem. The other are mysql-connector-python and PyMySQL.PyMySQL is an alternative you can use if mysqlclient does not work. Though it rarely happens. mysql-connector-python is the official MySQL connector from Oracle, and it needs a tiny more steps than PyMySQL and mysqlclient. Still, mysqlclient is robust and highly preferred when working with Django.

Step 1: Install the Connector

pip install mysqlclient

If you use the pipenv package manager, you will do:

pipenv install mysqlclient

If that doesn’t work on your system (especially on Windows), you can tryPyMySQL as an alternative:

pip install PyMySQL

If you use the pipenv package manager, you will do:

pipenv install PyMySQL

If you use this, you have to update inside your Django project folder (the one with settings.py), open or create a file named __init__.py and add:

import pymysql

pymysql.install_as_MySQLdb()

This line basically tells Django:

“Hey, whenever you see MySQLdb, just use PyMySQL instead.”

Step 2: Update settings.py

Now, tell Django to use MySQL.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',   # or IP address
        'PORT': '3306',        # default MySQL port
    }
}

Step 3: Create the Database

In your MySQL shell, create a database:

CREATE DATABASE mydatabase CHARACTER SET UTF8;

Step 4: Run migration

python manage.py makemigrations
python manage.py migrate

Additional Step: Using mysql-connector-python

If you use mysql-connector-python, you run the command like this:

pip install mysql-connector-python 

That is when you use the pip package manager. If you use the pipenv package manager, the command will be:

pipenv install mysql-connector-python

Then, modify the DATABASE dictionary in the Django project’s settings.py file, as you did in the previous step.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',   # or IP address
        'PORT': '3306',        # default MySQL port
        'OPTION': {
            'autocommit': True,
        }
    }
}

And boom! Your Django project is now running on MySQL.

Note: pip and pipenv have different configurations when working with Django. If you are unfamiliar or have limited knowledge about them, I encourage you to learn about them first. You can learn from my writing about pip vs pipenv here.

C. PostgreSQL

PostgreSQL is the most “Django-friendly” database. It works beautifully with Django’s ORM and supports advanced features.

Step 1: Install the Connector

The recommended package is psycopg2.

pip install psycopg2-binary

Or

pipenv install psycopg2-binary

Step 2: Update settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',  # default PostgreSQL port
    }
}

Step 3: Create the Database

In PostgreSQL shell:

CREATE DATABASE mydatabase;

Step 4: Run migration

python manage.py makemigrations
python manage.py migrate

Now Django is happily talking to PostgreSQL.

D. Switching Between Databases

The beauty of Django’s ORM is that your Python code doesn’t change when you switch databases. The only thing you change is the settings.py configuration.

For example, this query works the same across SQLite, MySQL, and PostgreSQL:

books = Book.objects.filter(author="George Orwell")

The difference is under the hood — how the database executes it. That’s why your choice of database matters.

Which Database Should You Use with Django?

Now that we’ve seen how to connect Django with SQLite, MySQL, and PostgreSQL, the natural question is: which one is the best for my project?

The truth is, it depends on your needs. Each database has its strengths, and the “best” choice isn’t the same for everyone. Let’s compare them side by side.

A. SQLite vs MySQL vs PostgreSQL

1. SQLite

  • Setup: Easiest (works by default)
  • Performance: Fine for small apps
  • Advanced Features: Very limited
  • Best Use Case: Learning, prototyping
  • Community Support: Moderate

2. MySQL

  • Setup: Simple, but needs extra setup
  • Performance: Good for medium-to-large apps
  • Advanced Features: Decent, improving
  • Best Use Case: Web apps, e-commerce, CMS
  • Community Support: Huge

3. PostgreSQL

  • Setup: Slightly more complex
  • Performance: Excellent, handles large scale
  • Advanced Features: Rich (JSON, full-text search, GIS)
  • Best Use Case: Scalable apps, enterprise systems
  • Community Support: Growing rapidly, loved by Django

B. When to Use SQLite

Stick with SQLite if you’re:

  • Just learning Django.
  • Building a portfolio project or prototype.
  • Creating a lightweight app where performance isn’t critical.

SQLite is like training wheels: perfect for learning but not built for high traffic.

C. When to Use MySQL

Choose MySQL if you:

  • Want something stable and widely supported.
  • Already have MySQL experience or infrastructure.
  • Are building a medium-to-large web app (e-commerce, CMS, SaaS).

MySQL is the “safe bet.” It’s everywhere, well-documented, and supported by almost every hosting service.

D. When to Use PostgreSQL

Go with PostgreSQL if you:

  • Want the best possible integration with Django (since Django supports many PostgreSQL-only features).
  • Need advanced functionality like JSON fields, full-text search, or geographic data.
  • Are building a project that needs to scale (enterprise, fintech, social networks).

PostgreSQL is the “Django darling” for a reason. It’s powerful, future-proof, and keeps up with the most demanding projects.

E. The Most Recommended Database for Django

If we had to pick a winner, it would be PostgreSQL.

Here’s why:

  • Django is built with PostgreSQL in mind. Some Django features (like JSONField, ArrayField, and GIS support) only work fully with PostgreSQL.
  • It’s highly reliable and scalable.
  • It’s open-source and has a passionate community.

That said, MySQL is still an excellent option if you prefer familiarity or hosting availability. And for beginners, SQLite is more than enough to get started.

Final Takeaway

  • Just learning Django? → Stick with SQLite.
  • Building a medium web app? → MySQL is fine.
  • Going enterprise or want long-term scalability? → PostgreSQL all the way.

The beauty of Django is that switching databases later is surprisingly easy. Start simple, and move to a stronger database when your project demands it.

“Heads up! I have tutorials on the Django Framework. Discover and Learn along with me here on my page. Whether you’re a complete beginner, experienced, or advanced, it doesn’t matter. My tutorials fit at all levels. Click here to begin with part 1: Introduction to Django

Hello all!

I would like you to support me as a Content Creator in Tech and Programming Tutor to take a look at my eBooks and buy them. These eBooks are about Programming with C++, which I have been using since I was in High School, and a Django Project tutorial eBook, an eBook I wrote for my students and viewers. This Django Tutorial is ideal for beginners who want to build a project and use it as a portfolio on GitHub.

**Click here to view and buy the Programming with C++** eBook.

**Click here to view and buy the Django Project Tutorial** eBook.

Your support means a lot to me. Thank you! 🙏

A message from our Founder

Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.

Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community. ❤️

If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, **Instagram. You can also subscribe to our [weekly newsletter](https://newsletter.plainenglish.io/)**.

And before you go, don’t forget to clap and follow the writer️!


메타데이터
post_id
c6367ee599fe
slug
django-and-databases-how-to-connect-relational-databases-and-which-one-you-should-choose-c6367ee599fe
url
https://python.plainenglish.io/django-and-databases-how-to-connect-relational-databases-and-which-one-you-should-choose-c6367ee599fe
canonical_url
https://python.plainenglish.io/django-and-databases-how-to-connect-relational-databases-and-which-one-you-should-choose-c6367ee599fe
author_url
https://medium.com/@zain169
status
ok
fetched_at
2026-08-11 23:03:24