Labs ICT
โญ Pro Login

Migrations

How Django evolves your database schema.

What Are Migrations?

Migrations are Django's way of propagating changes you make to your models into your database schema. Think of them as version control for your database structure.

When you add a field, rename a column, or create a new table, you need a migration to tell the database about the change. Django tracks all of this for you.

Creating Migrations

After you modify your models, run this command to generate migration files:


python manage.py makemigrations
    

Django compares your current models against the previous state and creates a migration file describing the changes. You'll see output like "Migrations for 'blog': 0002_post_published.py".

You can review what Django plans to do before applying it:


python manage.py migrate --plan
    

Applying Migrations

Creating a migration doesn't change the database. You need to apply it:


python manage.py migrate
    

Django keeps track of which migrations have been applied in a special table called django_migrations. When you run migrate, it only applies migrations that haven't been run yet.

Try it Yourself โ†’

Reading Migration SQL

Curious about what SQL Django generates? Use sqlmigrate to see the raw SQL:


python manage.py sqlmigrate blog 0001
    

This is useful for understanding what Django does behind the scenes and for debugging schema issues. You'll see CREATE TABLE statements, ALTER TABLE commands, and more.

The --fake Flag

Sometimes you need to mark a migration as applied without actually running it โ€” maybe you applied the changes manually or it's a data migration you don't want to run again.


python manage.py migrate blog 0002 --fake
    

Use this sparingly. Faking migrations can leave your database in an inconsistent state if you're not careful. Always make sure you know what you're doing before using --fake.

๐Ÿงช Quick Quiz

What does a Django migration do?