0
0
DjangoHow-ToBeginner · 3 min read

How to Use makemigrations in Django: Syntax and Examples

Use the python manage.py makemigrations command in Django to create migration files that reflect changes in your models. This command prepares the database schema updates but does not apply them; use python manage.py migrate to apply changes.
📐

Syntax

The basic syntax for creating migrations in Django is:

  • python manage.py makemigrations: Creates migration files for all apps with model changes.
  • python manage.py makemigrations appname: Creates migration files only for the specified app.

This command scans your models.py files for changes and generates migration scripts accordingly.

bash
python manage.py makemigrations
python manage.py makemigrations appname
💻

Example

This example shows how to create a new model and generate migrations for it.

First, add a model in your Django app's models.py:

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

# After saving this file, run the command below to create migrations:
💻

Example (continued)

Run the following command in your terminal inside the Django project directory:

bash
python manage.py makemigrations
Output
Migrations for 'yourappname': yourappname/migrations/0001_initial.py - Create model Book
⚠️

Common Pitfalls

  • Forgetting to specify the app name when you want migrations only for one app can create migrations for all apps.
  • Running makemigrations does not apply changes to the database; you must run python manage.py migrate afterward.
  • Not saving model changes before running makemigrations will result in no new migrations.
  • Conflicts can occur if multiple developers create migrations separately; resolve by merging migration files carefully.
bash
## Wrong: Running migrate without makemigrations
python manage.py migrate

## Right: Run makemigrations first, then migrate
python manage.py makemigrations
python manage.py migrate
📊

Quick Reference

CommandDescription
python manage.py makemigrationsCreate migration files for all apps with model changes
python manage.py makemigrations appnameCreate migration files for a specific app
python manage.py migrateApply migrations to update the database schema
python manage.py showmigrationsList all migrations and their applied status

Key Takeaways

Run python manage.py makemigrations to create migration files after changing models.
Specify the app name to limit migrations to that app only.
Always run python manage.py migrate after makemigrations to apply changes to the database.
Save your model changes before running makemigrations to detect updates.
Resolve migration conflicts carefully when working in teams.