Of course! This is a very common and powerful combination for building web applications. Let's break down what each component is, how they work together, and walk through a practical example.

The Big Picture: A Three-Layered Architecture
Think of your web application as a three-tiered system, and Python, Django, and MySQL each play a distinct role:
| Component | Role | Analogy |
|---|---|---|
| Python | The Language. The fundamental tool used to write the application's logic. | The Blueprint. It defines the rules and structure of your house. |
| Django | The Web Framework. A pre-built set of tools and libraries (written in Python) that speeds up development by handling common web tasks. | The Construction Kit. It provides the walls, windows, doors, and plumbing so you don't have to build everything from scratch. |
| MySQL | The Database. A system for storing, organizing, and retrieving your application's persistent data (like user info, posts, products). | The Foundation & Storage Room. It's where the house is built and where all your belongings (data) are kept safely. |
How they connect:
- User Request: A user visits your website (e.g.,
yourwebsite.com/products/). - Django (The Web Server): Django's web server receives the request. It looks at the URL (
/products/) and decides which part of your code to run. - Python (The Logic): Django executes your Python code. This code might need to get data from the database.
- Django (The ORM): Your Python code doesn't speak SQL directly. Instead, it uses Django's Object-Relational Mapper (ORM). The ORM translates your Python commands into SQL queries.
- MySQL (The Database): The SQL query is sent to the MySQL database. MySQL executes the query (e.g.,
SELECT * FROM products WHERE category = 'electronics';) and sends the results back. - The Journey Back: The data travels back up the chain:
- MySQL returns the raw data.
- The ORM converts the data back into Python objects (e.g., a list of
Productobjects). - Your Python code processes these objects, generates an HTML page, and sends it back to the user's browser.
Key Concepts: Django's ORM (The Bridge)
The most important concept for this trio is the ORM. It's what makes interacting with the database so easy in Django. Instead of writing raw SQL like this:
INSERT INTO myapp_author (name, birth_date) VALUES ('J.K. Rowling', '1965-07-31');
You write simple, readable Python like this:

# In your Django views.py or models.py from .models import Author # Create an author object author = Author(name="J.K. Rowling", birth_date="1965-07-31") # Save the object to the database. Django generates and runs the SQL for you! author.save()
The ORM supports all major database operations (Create, Read, Update, Delete - CRUD) and even handles complex queries, database connections, and security (like preventing SQL injection).
Step-by-Step Guide: Building a Simple To-Do App
Let's build a basic application with a Task model that stores a title and a due date in a MySQL database.
Step 1: Prerequisites
- Python: Installed on your system.
- MySQL Server: Installed and running. You should know the root password.
- Python Virtual Environment: It's a best practice to keep your project's dependencies isolated.
# Create and activate a virtual environment python -m venv venv # On Windows: # venv\Scripts\activate # On macOS/Linux: # source venv/bin/activate
Step 2: Install Required Packages
We need Django for the framework and mysqlclient or mysql-connector-python as the database adapter. mysqlclient is very common and performant.
pip install django mysqlclient
Step 3: Create a Django Project and App
# Create a new Django project django-admin startproject myproject # Navigate into the project directory cd myproject # Create a new app to handle our to-do tasks python manage.py startapp tasks
Step 4: Configure Django to Use MySQL
-
Create the MySQL Database: Connect to your MySQL server and create a database for your project.
(图片来源网络,侵删)-- Log in to MySQL (e.g., mysql -u root -p) CREATE DATABASE myproject_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
Configure
settings.py: Openmyproject/settings.pyand tell Django about your new database.# myproject/settings.py # ... (other settings) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # The database engine 'NAME': 'myproject_db', # The name of the database you created 'USER': 'root', # Your MySQL username 'PASSWORD': 'your_mysql_password', # Your MySQL password 'HOST': '127.0.0.1', # Or 'localhost' 'PORT': '3306', # Default MySQL port 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } # Add your new 'tasks' app to INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tasks', # Add this line ]
Step 5: Define the Model (The Database Table)
This is where we define the structure of our Task table in the database. Open tasks/models.py:
# tasks/models.py
from django.db import models
class Task(models.Model):= models.CharField(max_length=200)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.title
Step 6: Create and Apply Database Migrations
Migrations are Django's way of synchronizing your Python models with the actual database schema.
# This command inspects your models.py files and creates migration files python manage.py makemigrations # This command applies the migrations to the database, creating the tables python manage.py migrate
After running migrate, you will see tables like tasks_task created inside your myproject_db in MySQL.
Step 7: Use the Model in the Admin Panel
Let's make it easy to add tasks through Django's built-in admin interface.
-
Register the model: Open
tasks/admin.pyand register yourTaskmodel.# tasks/admin.py from django.contrib import admin from .models import Task admin.site.register(Task)
-
Create a superuser: To access the admin panel, you need an admin account.
python manage.py createsuperuser
Follow the prompts to create a username, email, and password.
-
Run the server and test it:
python manage.py runserver
Now, open your browser and go to
http://127.0.0.1:8000/admin/. Log in with the superuser credentials you just created. You should see a "Tasks" section where you can add, edit, and deleteTaskobjects. When you add one, the data is being saved directly to your MySQL database!
Troubleshooting Common Issues
-
mysqlclientInstallation Error: On some systems (especially Windows),mysqlclientcan be tricky to install. Ifpip install mysqlclientfails, you may need to install a MySQL development package first (e.g.,mysql-develon CentOS/RHEL ordefault-libmysqlclient-devon Ubuntu) or usemysql-connector-pythoninstead.pip install mysql-connector-python
If you use this, you only need to change one line in
settings.py:'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'driver': 'mysql.connector', # Add this line # ... other options }, -
Access denied for user 'root'@'localhost': Double-check your username and password insettings.py. Make sure the MySQL server is running and that the user has privileges on the database (myproject_db). -
django.db.utils.OperationalError: (2006, "MySQL server has gone away"): This can happen if a database connection is idle for too long. You can configure Django to close connections after each request insettings.py:DATABASES = { # ... 'CONN_MAX_AGE': 0, # Close the database connection after each request }
