How to Use the Migrate Command in Django: Syntax and Examples
Use the
python manage.py migrate command in Django to apply database migrations that create or update tables based on your models. This command runs migration files to keep your database schema in sync with your code.Syntax
The basic syntax of the migrate command is:
python manage.py migrate: Applies all pending migrations for all apps.python manage.py migrate app_label: Applies migrations only for the specified app.python manage.py migrate app_label migration_name: Applies migrations up to a specific migration for an app.
bash
python manage.py migrate [app_label] [migration_name]
Example
This example shows how to apply all migrations to set up your database after creating models.
bash
python manage.py makemigrations python manage.py migrate
Output
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, your_app
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying your_app.0001_initial... OK
Common Pitfalls
Common mistakes when using migrate include:
- Forgetting to run
makemigrationsbeforemigrate, so no new migrations are created. - Running
migratewithout specifying the app when you want to migrate only one app. - Trying to migrate to a migration name that does not exist.
- Not having the database configured correctly in
settings.py.
bash
python manage.py migrate your_app 0002_wrong_migration # Wrong migration name python manage.py migrate your_app 0002_correct_migration # Correct migration name
Quick Reference
| Command | Description |
|---|---|
| python manage.py migrate | Apply all migrations for all apps |
| python manage.py migrate app_label | Apply migrations for a specific app |
| python manage.py migrate app_label migration_name | Apply migrations up to a specific migration |
| python manage.py makemigrations | Create new migration files based on model changes |
Key Takeaways
Always run
makemigrations before migrate to create migration files.Use
migrate to apply database schema changes safely and keep your database in sync.You can migrate all apps or target specific apps and migrations with command arguments.
Check your database settings before running migrations to avoid connection errors.