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!