Open In App

How to integrate Mysql database with Django?

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. 

Installation

Let’s first understand how to install MySQL to install the Mysql database you can refer to the link below and install MySQL on your local machine.

https://dev.mysql.com/downloads/installer/

After downloading install the setup and set the admin and password for mysql. Then, install Django, and mysqlclient, for that you need to run the following command in your terminal.

pip install django
pip install mysqlclient

Steps to connect MySQL to Django

Step 1: Create a new project and start the process to connect django with mysql.

django-admin startproject MyDB

Step 2: Move to the MyDB folder.

cd MyDB

Note: You should have MySQL installed and be able to log in with appropriate privileges to create a database.

Step 3: Once you’re logged into MySQL, you can create a new database. Replace your_database_name with the desired name for your database.

CREATE DATABASE your_database_name

For better understanding you may refer to the article: Create a MySql database.

Step 4: Update the settings.py

Open settings.py here inside the DATABASES variable configure MySQL database values, and add values of your database.

Python3




DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': 'admin',
        'HOST':'localhost',
        'PORT':'3306',
    }
}


First, we have replaced the ‘django.db.backends.sqlite3’ to ‘django.db.backends.mysql’. This is basically indicating we shift SQLite to MySQL database.

  • NAME: It indicates the name of the database we want to connect.
  • USER: The MYSQL username is the one who has access to the database and manages it.
  • PASSWORD: It is the password of the database. 
  • HOST: It is indicated by “127.0.0.1” and “PORT” “3306” that the MySQL database is accessible at hostname “0.0.1” and on port “3306.”

Step 5: Run the server.

python manage.py runserver

Step 6: Run the migration command

python manage.py makemigrations

How to connect MySQL to Django

makemigration command

python manage.py migrate
How to connect MySQL to Django

Apply migrations


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads