Lesson 26 of 60 – Django Migrations
43%

Django Migrations

Django migrations are used to apply changes made to Django models to the database. They provide a structured way to create and update database tables when your models change.

Note: The two most commonly used migration commands are makemigrations and migrate.

1. What Are Django Migrations?

Migrations are files that describe changes to the structure of your database based on changes made to Django models.

For example, if you create a Student model, Django can generate a migration that describes how the corresponding database table should be created.

2. Why Are Migrations Needed?

Django models describe your application's data structure, while migrations help apply that structure to the database.

  • Create database tables
  • Add new fields
  • Change model fields
  • Remove fields
  • Rename fields
  • Delete models

3. Models and Migrations

Suppose you create this model:

class Student(models.Model):
    name = models.CharField(max_length=100)

Django needs to translate this model change into database operations. This is where migrations are used.

4. The makemigrations Command

The makemigrations command detects changes in your models and creates migration files.

python manage.py makemigrations

This command does not normally apply the changes to the database. It creates the migration instructions.

5. The migrate Command

The migrate command applies migration operations to the database.

python manage.py migrate

It uses migration files to bring the database schema into the required state.

6. Difference Between makemigrations and migrate

Command Purpose
makemigrations Creates migration files from model changes
migrate Applies migration operations to the database

A common workflow is to run makemigrations first and then migrate.

7. Migration Folder

Each Django app can have a migrations folder.

students/
├── migrations/
│   └── __init__.py
├── models.py
├── views.py
└── admin.py

Migration files for the app are normally stored inside this folder.

8. First Migration

When you create a model and run:

python manage.py makemigrations

Django may create a file such as:

students/migrations/0001_initial.py

The exact migration name and contents depend on your model changes.

9. Migration File

A migration file contains Python code describing database operations.

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Student',
            fields=[
                ...
            ],
        ),
    ]

Django generates these files automatically.

10. Migration Numbers

Migration files commonly use numbered names to show their order.

0001_initial.py
0002_student_email.py
0003_student_phone.py

Django uses migration dependencies to determine the correct order in which migrations should be applied.

11. Adding a New Field

Suppose the original model contains only a name:

class Student(models.Model):
    name = models.CharField(max_length=100)

Now add an email field:

class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

Run:

python manage.py makemigrations

Then:

python manage.py migrate

12. Adding a Field to Existing Records

When adding a non-nullable field to a model that already contains database records, Django may ask how existing records should receive a value.

For example:

phone = models.CharField(
    max_length=15
)

You may need to provide an appropriate default or allow blank/null values, depending on the application's requirements.

13. Changing a Field

Suppose you change the maximum length of a field:

name = models.CharField(
    max_length=150
)

Run:

python manage.py makemigrations
python manage.py migrate

Django generates and applies the required migration operation.

14. Removing a Field

If you remove a field from a model:

class Student(models.Model):
    name = models.CharField(max_length=100)

and the field previously existed, Django can detect the change when you run:

python manage.py makemigrations

After confirmation and creation of the migration, use:

python manage.py migrate

15. Renaming a Field

If a field is renamed, Django's migration system can generate a migration operation based on the detected model change.

For example:

student_name

could be changed to:

name

Review generated migrations carefully, especially when working with important production data.

16. Checking Migration Status

Use the showmigrations command to see migrations and their applied status.

python manage.py showmigrations

Applied migrations are normally shown with a marker such as [X].

17. Show Migrations for a Specific App

You can specify an app name:

python manage.py showmigrations students

This displays the migration status for the specified app.

18. Applying a Specific Migration

Django can migrate an app to a particular migration state.

python manage.py migrate students 0002

This is useful when you need to move the app's migration state to a particular point in its migration history.

19. Migrating Backward

You can migrate an app back to an earlier migration.

python manage.py migrate students 0001

This can unapply migrations after that migration in the dependency sequence. Use backward migrations carefully because database changes can affect data.

20. Zero Migration State

Using zero requests that Django unapply all migrations for the specified app.

python manage.py migrate students zero

This can reverse the app's migration state, but it should be used carefully, especially when the database contains important data.

21. Migration Dependencies

Migration files can depend on earlier migrations. Django uses these dependencies to determine the correct order of operations.

dependencies = [
    ('students', '0001_initial'),
]

This helps Django maintain a consistent migration history.

22. Migrations and Database Schema

The database schema describes the structure of database tables and fields. Migrations provide a controlled way to change that schema as your Django models evolve.

Model
  ↓
makemigrations
  ↓
Migration File
  ↓
migrate
  ↓
Database Schema

23. Migration and Data

Migrations primarily describe changes to database structure, but Django also supports data migrations for operations that transform or populate data.

For example, a data migration can be used to populate a new field based on existing records.

Data migrations should be designed carefully so that they work correctly with the application's data.

24. Empty Migration

You can create an empty migration when you need to write custom migration operations.

python manage.py makemigrations students --empty

This can be useful for custom data or database operations that are not automatically generated from model changes.

25. Migration Files in Version Control

Migration files are normally part of the application's source code and should generally be committed to version control.

This allows other developers and deployment environments to reproduce the database schema changes in the correct order.

students/
└── migrations/
    ├── __init__.py
    ├── 0001_initial.py
    └── 0002_student_email.py

26. Common Migration Mistakes

  • Changing models but forgetting to run makemigrations
  • Creating migrations but forgetting to run migrate
  • Deleting migration files without understanding the consequences
  • Ignoring migration conflicts
  • Adding required fields without considering existing records
  • Manually changing database tables without coordinating with migrations
  • Running destructive migration operations without checking data

27. Migration Workflow

Step 1: Change the model.

class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

Step 2: Create migration.

python manage.py makemigrations

Step 3: Apply migration.

python manage.py migrate

Step 4: Check migration status.

python manage.py showmigrations

28. Migration Commands

Command Purpose
makemigrations Create migration files
migrate Apply migrations
showmigrations Show migration status
sqlmigrate Display SQL generated for a migration

For example:

python manage.py sqlmigrate students 0001

29. Complete Migration Example

Step 1: Create a model

from django.db import models

class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    email = models.EmailField()

    age = models.IntegerField()

Step 2: Create migration

python manage.py makemigrations

Step 3: Apply migration

python manage.py migrate

Step 4: Check status

python manage.py showmigrations

The database schema now reflects the model changes after the migration has been successfully applied.

30. Summary of Django Migrations

Django migrations provide a systematic way to keep the database structure synchronized with Django models.

  • Migrations describe database schema changes.
  • makemigrations creates migration files.
  • migrate applies migrations.
  • Migration files are stored inside an app's migrations folder.
  • showmigrations displays migration status.
  • Migration files normally belong in version control.
  • Models can be changed and new migrations can be generated.
  • Data migrations can perform custom data operations.
  • Migrations should be reviewed carefully when they affect existing data.
  • Migration dependencies help Django maintain the correct order.

📌 Key Points

  • Django migrations connect model changes with database schema changes.
  • Use python manage.py makemigrations to create migration files.
  • Use python manage.py migrate to apply migrations.
  • Use python manage.py showmigrations to check migration status.
  • Migrations are stored inside the app's migrations folder.
  • Migration files should normally be included in version control.
  • Be careful when adding, removing, or changing fields in tables containing existing data.
  • Django can also create custom data migrations.
  • Migration dependencies control the order of migration operations.

🧠 Quick Quiz

Question: Which Django command creates migration files based on changes made to models?