How to Create Migration in Django: Step-by-Step Guide
To create a migration in Django, use the
python manage.py makemigrations command which generates migration files based on your model changes. Then apply these changes to the database with python manage.py migrate.Syntax
The main commands to create and apply migrations in Django are:
python manage.py makemigrations [app_label]: Creates migration files for model changes in the specified app or all apps if none specified.python manage.py migrate: Applies all pending migrations to the database.
bash
python manage.py makemigrations [app_label] python manage.py migrate
Example
This example shows how to create a new model and generate a migration for it, then apply the migration to update the database.
bash
1. Define a new model in your Django app's <code>models.py</code> file: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) 2. Run the command to create migration files: python manage.py makemigrations 3. Apply the migration to update the database: python manage.py migrate
Output
Migrations for 'yourapp':
yourapp/migrations/0001_initial.py
- Create model Book
Operations to perform:
Apply all migrations: yourapp
Running migrations:
Applying yourapp.0001_initial... OK
Common Pitfalls
Common mistakes when creating migrations include:
- Not running
makemigrationsafter changing models, so migrations are not created. - Forgetting to run
migrateto apply changes to the database. - Manually editing migration files, which can cause errors.
- Not specifying the app label when working with multiple apps, leading to confusion.
Always let Django generate migration files automatically and apply them promptly.
bash
Wrong way: # Change models.py but forget to run makemigrations Right way: python manage.py makemigrations python manage.py migrate
Quick Reference
| Command | Purpose |
|---|---|
| python manage.py makemigrations | Create migration files for 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 migration |
Key Takeaways
Always run
makemigrations after changing your models to create migration files.Use
migrate to apply migrations and update your database schema.Never manually edit migration files unless you know exactly what you are doing.
Specify the app label in commands when working with multiple apps to avoid confusion.
Check migration status with
showmigrations to track applied changes.