Database Migrations

  • Learn how Django handles database schema changes using migrations and version control system.
  • What are Database Migrations?

    Database Migrations are Django’s way of tracking and applying changes made to models into the database without losing data.

    Any change in:

    • Model fields

    • Field types

    • Table structure

    → must go through migrations

    Simple Meaning

    Migrations = Version control for your database

    Why Migrations are Needed

    Without Migrations

    • Manual SQL needed

    • Risk of data loss

    • Hard to manage changes

    • Errors in production

    With Migrations

    • Automatic table updates

    • Safe schema changes

    • Tracks database history

    • Works in teams

    Migration Workflow (Step-by-Step)

    Migration Flow Diagram

    models.py change

          ↓

    makemigrations

          ↓

    migration file created

          ↓

    migrate

          ↓

    database updated

    Create / Modify Model

Initial Student Model

This model defines the database structure.

from django.db import models

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

Run makemigrations

Create Migration File

python manage.py makemigrations
  • What Happens?

    • Django checks model changes

    • Creates a file in:

    app_name/migrations/0001_initial.py

    This file contains Python code, not SQL.

    Migration File Structure

Sample Migration File

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Student',
            fields=[
                ('id', models.AutoField(primary_key=True)),
                ('name', models.CharField(max_length=100)),
                ('age', models.IntegerField()),
            ],
        ),
    ]

Run migrate

Apply Migration to Database

python manage.py migrate
  • What Happens?

    • Migration file is executed

    • Table is created/updated in DB

    • Migration recorded in django_migrations table

    Modifying Models & Re-Migrating

Add New Field to Model

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

Migration Commands

python manage.py makemigrations
python manage.py migrate
  • Django creates new migration, not overwriting old one.

    Importance of Migrations (Key Points)

    1. Tracks Database Changes

    • Every change has a migration file

    • Easy rollback

    2. Prevents Data Loss

    • Safely alters tables

    • Handles default values & nulls

    3. Team Collaboration

    • Same database structure for all developers

    • Works well with Git

    4. Environment Consistency

    • Same schema in:

      • Development

      • Testing

      • Production

    Common Migration Commands

Show All Migrations

python manage.py showmigrations

Migrate Specific App

python manage.py migrate app_name

Rollback Migration

python manage.py migrate app_name 0001
  • Common Migration Errors (Beginner Level)

    Error

    Reason

    Solution

    Field added without default

    Existing data

    Provide default

    Forgot migrate

    Table not updated

    Run migrate

    Deleted migration file

    Inconsistent DB

    Re-create migrations

Full Migration Workflow Example

1. Create Student model
2. makemigrations → 0001_initial.py
3. migrate → Student table created
4. Add email field
5. makemigrations → 0002_add_email.py
6. migrate → Table updated safely