Saturday, March 7, 2026

Step-by-step process of using MySQL with Django 2

 1. Install MySQL and Python Packages

Before starting, you need to have MySQL installed on your computer. Then, install the Python package mysqlclient which allows Django to connect to MySQL.

pip install mysqlclient

2. Create a Database in MySQL

You need a database for your Django project. For example:

CREATE DATABASE school;

This database will store all your tables and data.


3. Configure Django to Use MySQL

In your Django project, open the settings.py file and modify the DATABASES section to connect Django to MySQL:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'school',
        'USER': 'root',         # Your MySQL username
        'PASSWORD': 'password', # Your MySQL password
        'HOST': 'localhost',    # Or your server address
        'PORT': '3306',         # Default MySQL port
    }
}

4. Create Models in Django

Models in Django represent tables in the database. For example, a Student table:

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=50)
    course = models.CharField(max_length=50)

5. Apply Migrations

Django uses migrations to create tables in the database based on your models.

python manage.py makemigrations
python manage.py migrate

This will create the corresponding tables in MySQL.


6. Add Data via Django Admin or Shell

You can add data to your MySQL database using:

Django Admin

  • Create a superuser:

python manage.py createsuperuser
  • Log in to /admin and add records.

Django Shell

python manage.py shell
from app.models import Student
student = Student(name="John", course="Computer Science")
student.save()

7. Query Data

You can retrieve data using Django ORM (Object Relational Mapping), which automatically generates SQL for MySQL.

# Get all students
students = Student.objects.all()

# Filter students by course
cs_students = Student.objects.filter(course="Computer Science")

8. Update and Delete Data

# Update
student = Student.objects.get(id=1)
student.course = "Mathematics"
student.save()

# Delete
student = Student.objects.get(id=1)
student.delete()

9. Deploy Application

Once your Django app works locally with MySQL, you can deploy it to a server (like DigitalOcean or AWS) so users can access it online.


Summary of the Process

StepAction
1Install MySQL and Python packages
2Create a database in MySQL
3Configure Django settings to use MySQL
4Create models to represent tables
5Make migrations to create tables in MySQL
6Add data using admin or shell
7Query data using Django ORM
8Update or delete data
9Deploy the application


0 comments:

Post a Comment

 

BEST COMPUTER GUIDE Written by Abigail Odenigbo, Published @ 2014 by NOBIGDEAL(Ipietoon)