Django Migrations are a version control system for a database schema. They represent a set of operations (written in Python) that transition the database from one state to another, keeping it synchronized with the Django Models.
When you change a Model (e.g., add a new column), the database doesn’t know about it automatically. Migrations are instructions that tell the database exactly how to alter its tables to match your new Python code.
- Developer changes
models.py. - Developer runs
python manage.py makemigrations. - Django compares the models to the previous state and generates a migration file (Python script).
- Developer runs
python manage.py migrate. - Django translates the migration file into SQL
ALTER TABLE/CREATE TABLEstatements and executes them. - Django records that this migration was applied in the
django_migrationstable.
graph LR A[Update models.py] -->|makemigrations| B(Migration File 0002_add_field.py) B -->|migrate| C[(Database Schema Updated)]
Migrations are like architectural blueprints showing modifications to a building. If you want to add a room, you don’t just magically have a room. You draw up the plans (makemigrations) and then the construction crew follows the plans to build it (migrate).
# Generate the migration files
python manage.py makemigrations
# Apply the changes to the database
python manage.py migrate- Auto-generated based on model differences.
- Can be applied forward or rolled backward.
- Tracked in a special database table to prevent applying the same migration twice.
- Built from: Django Model — migrations reflect model changes.
- Related: Django ORM — works closely with the ORM.
- Related: Django Project — managed via manage.py.
- Related: Python — migrations are just Python files.
- Deleting migration files manually can cause the database state and Django state to fall out of sync, requiring complex manual fixes.
- Adding a non-nullable field to an existing table requires providing a default value.