๐ Django makemigrations vs migrate – Complete Guide
Django provides two core commands for database management:
makemigrations– prepares changesmigrate– applies changes
They look similar, but they perform completely different roles in the database lifecycle.
๐ Table of Contents
- Overview
- What is makemigrations?
- What is migrate?
- Full Workflow
- Database Mapping (Simple Math Model)
- CLI Examples
- Comparison Table
- Best Practices
- Related Articles
๐ง Overview
This avoids direct risky changes to the database and ensures version control for schema evolution.
⚙️ What is makemigrations?
This command detects changes in models.py and creates migration files.
Command
python manage.py makemigrations
What it does internally:
- Scans model changes
- Compares with last migration
- Generates Python migration scripts
Example Output
View CLI Output
Migrations for 'app':
app/migrations/0002_add_age_field.py
- Add field age to Student
Important Idea
It does NOT change the database. It only prepares instructions.
๐ What is migrate?
This command applies migration files to the database.
Command
python manage.py migrate
What it does internally:
- Reads migration files
- Converts them into SQL
- Executes SQL on database
Example Output
View CLI Output
Applying app.0002_add_age_field... OK
๐ Django Migration Workflow
Step-by-step process:
- Create or modify model
- Run makemigrations
- Generate migration file
- Run migrate
- Database updated
๐ Database Mapping (Simple Mathematical Model)
Think of Django migrations as a transformation function:
\[ Database_{new} = f(Database_{old}, Migration) \]
Explanation:
- Database_old = current schema
- Migration = instructions (like rules)
- f() = transformation engine (Django ORM)
Another way to think:
\[ Schema_{t+1} = Schema_t + \Delta Changes \]
- \( \Delta Changes \) = new fields, tables, deletions
๐ฅ️ CLI Example Workflow
Step 1: Create model
class Student(models.Model):
name = models.CharField(max_length=100)
Step 2: Run makemigrations
python manage.py makemigrations
Step 3: Migration file created
Generated File
0001_initial.py
Step 4: Apply migration
python manage.py migrate
Step 5: Database updated
⚖️ makemigrations vs migrate
| Feature | makemigrations | migrate |
|---|---|---|
| Purpose | Create migration files | Apply migrations to DB |
| Affects DB? | No | Yes |
| Output | Python migration scripts | SQL execution |
| Usage stage | Development step | Deployment/runtime step |
๐ก Best Practices
- Always run
makemigrationsafter model changes - Commit migration files in Git
- Run
migratebefore deploying - Never edit migration files manually unless necessary
๐ฏ Final Summary
makemigrations prepares changes.
migrate applies changes.
Together, they ensure safe and structured database evolution in Django applications.