Recommended preparation: set up a Django project and read the Django tutorial overview before trying the code.
Django connects to MySQL through its database backend and a supported driver such as mysqlclient. Define a model in Python, generate migrations and apply them rather than manually creating the main table.
Install Django 5.2 LTS and the MySQL database driver
# Run in an activated virtual environment
python -m pip install "Django>=5.2,<5.3" mysqlclient
You need a running MySQL server, an existing database and a database user with suitable permissions. New learners can use SQLite for early lessons before changing the engine to MySQL.
Run in a MySQL administration tool with appropriate privileges
CREATE DATABASE django_demo CHARACTER SET utf8mb4;
CREATE USER 'django_user'@'localhost' IDENTIFIED BY 'replace-with-a-strong-password';
GRANT ALL PRIVILEGES ON django_demo.* TO 'django_user'@'localhost';
plus2net_demo/settings.py — read credentials from environment
import os
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": os.environ["DJANGO_DB_NAME"],
"USER": os.environ["DJANGO_DB_USER"],
"PASSWORD": os.environ["DJANGO_DB_PASSWORD"],
"HOST": os.getenv("DJANGO_DB_HOST", "127.0.0.1"),
"PORT": os.getenv("DJANGO_DB_PORT", "3306"),
"OPTIONS": {"charset": "utf8mb4"},
}
}
Putting database credentials directly into source code risks accidental exposure. Environment variables keep credentials out of the page’s code and avoid accidental source-control exposure. See the official Django MySQL backend notes.
Run from the folder containing manage.py
python manage.py startapp students
students/models.py — shared model used in the remaining database lessons
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
cl = models.CharField(max_length=20, db_column="class")
mark = models.PositiveSmallIntegerField()
gender = models.CharField(max_length=20)
def __str__(self):
return self.name
The model defines name, cl, mark and gender. The db_column="class" setting preserves the SQL column name class where existing examples need it. Django adds a primary key automatically unless configured otherwise.
plus2net_demo/settings.py
# Add this app name to the existing INSTALLED_APPS list
"students",
Generate and apply the student table migration
python manage.py makemigrations students
python manage.py migrate
python manage.py showmigrations students
makemigrations prepares schema changes as migration files; migrate applies them to the configured database. Run them in that order. Generate migration files with your installed Django version rather than copying migration output from another project.
View SQL generated for the initial migration
python manage.py sqlmigrate students 0001
The SQL depends on your Django and MySQL versions. Table names generally follow app_model, such as students_student; do not assume an old example’s student_student or exact SQL will always match.
Open the Django shell
python manage.py shell
Check the model and query the first records
from students.models import Student
print(Student.objects.count())
print(Student.objects.order_by("id")[:5])
Next, learn how to insert a student using a validated form, insert batches, query and display rows or manage records using the admin interface.
mysqlclient wheel/build for your Python environment.INSTALLED_APPS, makemigrations and migrate.Validate project configuration
python manage.py check
Check the status of the students app migrations
python manage.py showmigrations students
Open the configured database client when available
python manage.py dbshell
Inspect a legacy database schema (for database-first projects)
python manage.py inspectdb
inspectdb is helpful when connecting Django to a database with existing tables. Generated models should be reviewed rather than pasted into production unchanged.
Illustration of non-secret variables; keep password out of public examples
# Environment variables for the DB credentials, shown as names only
DJANGO_DB_NAME=django_demo
DJANGO_DB_USER=django_user
DJANGO_DB_HOST=127.0.0.1
DJANGO_DB_PORT=3306
Verify that the configured database accepts a simple query
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("SELECT 1")
print(cursor.fetchone())
Expected output
(1,)
Django shell — insert one example record
from students.models import Student
Student.objects.create(name="Alex", cl="Four", mark=78, gender="male")
Count students with marks of 60 or above
from students.models import Student
print(Student.objects.filter(mark__gte=60).count())
Preview pending migration steps before applying them
python manage.py migrate --plan
Yes. The Django ORM and model examples work with SQLite for local learning. For MySQL-specific behavior, configure a MySQL server.
Generally no. Change models and run makemigrations, then inspect and review the resulting migration before applying it.
Normally Django migrations create it. Mixing manual schema changes and migrations may cause inconsistent model state.
Previous: CSS, JavaScript, jQuery and static files
Next: Insert form data
Browse the complete Django tutorial series.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.