</>
Skip to content
Django lessons (16/43)

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

  1. Always create migrations after model changes
  2. Review migration files before applying
  3. Test migrations on development first
  4. Use data migrations for data changes

Mini Practice

  1. Create a model and make migrations
  2. Apply migrations
  3. Rollback a migration
  4. 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.