← Back to Chapters

Creating & Applying Migrations

? Creating & Applying Migrations

? Quick Overview

Django migrations help track and apply changes made to your models into the database schema using the makemigrations and migrate commands.

? Key Concepts

  • Migrations are version-controlled database schema changes
  • Automatically generated from model changes
  • Applied incrementally and safely

? Syntax & Theory

makemigrations creates migration files, while migrate applies them to the database.

? Code Examples

? View Code Example
# Create migration files for all apps
python manage.py makemigrations
? View Code Example
# Apply all pending migrations
python manage.py migrate
? View Code Example
# Django model with a newly added field
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()

?️ Migration Playground

Simulate the workflow! Add a field to the model, generate a migration file, and apply it to the database.

? models.py
class Product(models.Model): name = CharField()
? migrations/0001_initial.py
# No migrations generated yet...
?️ Database Schema (PostgreSQL/SQLite)
TABLE: app_product ------------------ - id (INT) - name (VARCHAR)
Status: Database out of sync with models

? Live Output / Explanation

After running migrations, Django updates the database schema to match the models. New tables or columns become available without data loss.

? Interactive Concept

Think of migrations as a timeline: each migration is a step that moves your database forward safely, one change at a time.

? Use Cases

  • Adding new fields to existing models
  • Modifying field types
  • Keeping team databases in sync

✅ Tips & Best Practices

  • Always run makemigrations before migrate
  • Commit migration files to version control
  • Review generated migrations before applying

? Try It Yourself

  • Create a model and generate migrations
  • Apply them using migrate
  • Add another field and repeat the process