A migration is a file describing changes to the database schema. Django tracks the state of your models and generates SQL automatically.
Workflow
# 1. Change a model in models.py
# 2. Create the migration file
python manage.py makemigrations
# 3. Apply it to the database
python manage.py migrate
makemigrations — creating a file
python manage.py makemigrations # for all applications
python manage.py makemigrations tasks # only for tasks
python manage.py makemigrations --name add_priority # with a custom name
Creates a file like tasks/migrations/0002_task_priority.py:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('tasks', '0001_initial')]
operations = [
migrations.AddField(
model_name='task',
name='priority',
field=models.IntegerField(default=0),
),
]
migrate — applying migrations
python manage.py migrate # apply all
python manage.py migrate tasks # only for one app
python manage.py migrate tasks 0001 # roll back to a version
python manage.py migrate tasks zero # roll back everything
Migration status
python manage.py showmigrations
# [X] tasks.0001_initial ← applied
# [X] tasks.0002_task_priority
# [ ] tasks.0003_task_due_date ← not yet applied
What NOT to do
# ❌ Do not delete migration files manually
# ❌ Do not edit already-applied migrations
# ❌ Do not name fields with reserved SQL keywords
squashmigrations — merging migrations
# Merge migrations 0001-0010 into one
python manage.py squashmigrations tasks 0001 0010
Useful when many migrations have accumulated. After squashing, the old files can be deleted once all environments have been updated.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!