Django — Migrations
What are Migrations?
Migrations are Django's way of propagating changes you make to your models into your database schema.
Create Migrations
python manage.py makemigrations
python manage.py makemigrations blog
Apply Migrations
python manage.py migrate
Migration Files
blog/migrations/
├── 0001_initial.py
├── 0002_post_published.py
└── __init__.py
Migration Operations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='published',
field=models.BooleanField(default=False),
),
]
Common Commands
python manage.py showmigrations # Show migration status
python manage.py sqlmigrate blog 0001 # Show SQL for migration
python manage.py migrate blog 0002 # Migrate to specific version
python manage.py migrate blog zero # Reverse all migrations
Rollback
# Rollback last migration
python manage.py migrate blog 0001
Best Practices
- Always create migrations after model changes
- Review migration files before applying
- Test migrations on development first
- Use data migrations for data changes
Mini Practice
- Create a model and make migrations
- Apply migrations
- Rollback a migration
- View migration SQL
Up Next
Continue with Admin — Django's admin interface.
Related Topics
Frequently Asked Questions about Migrations
What is Migrations in Django?
Migrations is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Migrations?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Migrations.
Why is Migrations important in Django?
Migrations is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.