How to Run Migration in Django: Step-by-Step Guide
To run migrations in Django, use the
python manage.py makemigrations command to create migration files, then apply them with python manage.py migrate. These commands update your database schema to match your models.Syntax
The migration process in Django involves two main commands:
python manage.py makemigrations: Creates new migration files based on changes in your models.python manage.py migrate: Applies the migrations to your database, updating its structure.
Use these commands in your project directory where manage.py is located.
bash
python manage.py makemigrations python manage.py migrate
Example
This example shows how to add a new field to a Django model and run migrations to update the database.
python and bash
1. Edit your model in <code>models.py</code> to add a new field, for example: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) published_date = models.DateField(null=True) # New field added 2. Run the following commands in your terminal: python manage.py makemigrations python manage.py migrate
Output
Migrations for 'yourapp':
yourapp/migrations/0002_auto.py
- Add field published_date to book
Operations to perform:
Apply all migrations: yourapp
Running migrations:
Applying yourapp.0002_auto... OK
Common Pitfalls
Common mistakes when running migrations include:
- Not running
makemigrationsafter changing models, so no migration files are created. - Running
migratewithout migration files, causing no changes to the database. - Forgetting to activate the correct virtual environment or running commands outside the Django project folder.
- Conflicts in migration files when multiple developers create migrations simultaneously.
Always check the output of makemigrations to confirm migration files are created before applying them.
bash
Wrong way: # Change models.py but forget to run makemigrations python manage.py migrate # No changes applied because no migration files exist Right way: python manage.py makemigrations python manage.py migrate
Quick Reference
| Command | Purpose |
|---|---|
| python manage.py makemigrations | Create migration files from model changes |
| python manage.py migrate | Apply migrations to update the database |
| python manage.py showmigrations | List all migrations and their status |
| python manage.py sqlmigrate | Show SQL for a specific migration |
Key Takeaways
Always run
makemigrations after changing models to create migration files.Use
migrate to apply migrations and update your database schema.Run migration commands inside your Django project directory where
manage.py is located.Check migration outputs to confirm changes are applied successfully.
Avoid migration conflicts by coordinating with your team when working on the same app.