Skip to main content

Guide to Database Connection in Django

Connecting to MySQL

To connect to a MySQL database in Django, you first need to install the mysqlclient package and add it to your requirements.txt file. Use the following command to install this package:

pip install mysqlclient

Then, add the following command to your project's run.sh file:

apt-get install python3-dev default-libmysqlclient-dev build-essential

Next, you need to configure the database connection settings in your Django project's settings.py file. Enter the database information in the DATABASES section of the settings.py file. Here is an example of the MySQL database connection settings in Django:

import os

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
}

Connecting to PostgreSQL

To connect to a PostgreSQL database in Django, you first need to install the psycopg2 package and add it to your requirements.txt file. Use the following command to install this package:

pip install psycopg2

In your project's settings.py file, configure the database connection settings for PostgreSQL. Here is an example of the PostgreSQL database connection settings in Django:

import os

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
}

To use connection pooling in Django, you can use the django-db-connection-pool package. Use the following command to install this package:

pip install django-db-connection-pool[all]

Then, configure the database connection settings in your Django project's settings.py file. Enter the database information in the DATABASES section of the settings.py file. Here is an example of the MySQL database connection settings with connection pooling in Django:

import os

DATABASES = {
'default': {
'ENGINE': 'dj_db_conn_pool.backends.mysql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
'POOL_OPTIONS': {
'POOL_SIZE': 10,
'MAX_OVERFLOW': 10,
'RECYCLE': 24 * 60 * 60 # 24H
}
}
}
caution

After configuring the database connection settings, you must run the following command to apply the changes:

python manage.py migrate