Migrations — makemigrations & migrate
Migrations are Django's way of propagating model changes to the database schema. They are version-controlled files that track every change you make to your models. Two key commands: makemigrations creates migration files, migrate applies them.
15 min•By Priygop Team•Updated 2026
Migration Commands
- python manage.py makemigrations — Create migration files from model changes
- python manage.py migrate — Apply pending migrations to database
- python manage.py showmigrations — List all migrations and their status
- python manage.py sqlmigrate app_name 0001 — Show SQL for a migration
- python manage.py migrate app_name zero — Revert all migrations for an app
- Migrations are stored in app/migrations/ directory
- Always commit migration files to version control
- Never edit migration files manually unless absolutely necessary
Migration Workflow
Migration Workflow
# Step 1: Make changes to your model
# blog/models.py
# class Post(models.Model):
# title = models.CharField(max_length=200)
# content = models.TextField()
# # NEW: adding a field
# views_count = models.IntegerField(default=0)
# Step 2: Create migration
# python manage.py makemigrations
# Output: Migrations for 'blog':
# blog/migrations/0002_post_views_count.py
# - Add field views_count to post
# Step 3: Review the SQL (optional)
# python manage.py sqlmigrate blog 0002
# Output: ALTER TABLE "blog_post"
# ADD COLUMN "views_count" integer DEFAULT 0 NOT NULL;
# Step 4: Apply migration
# python manage.py migrate
# Output: Applying blog.0002_post_views_count... OK
# Check migration status
# python manage.py showmigrations blog
# blog
# [X] 0001_initial
# [X] 0002_post_views_countTip
Tip
Use ForeignKey for many-to-one and ManyToManyField for many-to-many. Add related_name for clear reverse lookups.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Forgetting related_name on ForeignKey. Without it, reverse lookups use 'modelname_set'. Set related_name='comments' for clarity.
Practice Task
Note
(1) Create Post and Comment models with ForeignKey. (2) Add ManyToManyField for tags. (3) Test reverse lookups in the shell.
Quick Quiz
Key Takeaways
- Migrations are Django's way of propagating model changes to the database schema.
- python manage.py makemigrations — Create migration files from model changes
- python manage.py migrate — Apply pending migrations to database
- python manage.py showmigrations — List all migrations and their status