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
/adminand 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
| Step | Action |
|---|---|
| 1 | Install MySQL and Python packages |
| 2 | Create a database in MySQL |
| 3 | Configure Django settings to use MySQL |
| 4 | Create models to represent tables |
| 5 | Make migrations to create tables in MySQL |
| 6 | Add data using admin or shell |
| 7 | Query data using Django ORM |
| 8 | Update or delete data |
| 9 | Deploy the application |


0 comments:
Post a Comment