0
0
DjangoConceptBeginner · 3 min read

What is Migration in Django: Explanation and Example

In Django, migration is a way to update your database schema automatically when your models change. It tracks changes like adding or removing fields and applies them to the database without losing data.
⚙️

How It Works

Think of migrations like a diary that keeps track of every change you make to your database structure. When you change your Django models, migrations record those changes as steps. Later, you can apply these steps to your database to keep it in sync with your code.

This process is similar to updating a recipe book: if you add a new ingredient or change a step, you write it down so anyone cooking later knows the new instructions. Django migrations do this automatically, so your database always matches your models.

💻

Example

This example shows how to create a migration after adding a new field to a Django model and then apply it to update the database.

python
from django.db import models

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

# Later, add a new field:
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_year = models.IntegerField(null=True, blank=True)

# Commands to run in terminal:
# python manage.py makemigrations
# python manage.py migrate
Output
Migrations for 'yourapp': yourapp/migrations/0002_book_published_year.py - Add field published_year to book Operations to perform: Apply all migrations: yourapp Running migrations: Applying yourapp.0002_book_published_year... OK
🎯

When to Use

Use migrations whenever you change your Django models, such as adding, removing, or modifying fields or tables. This keeps your database structure up to date without manual changes.

For example, if you add a new feature that requires storing extra information about users or products, you create a migration to update the database accordingly. Migrations are essential in team projects to share database changes safely.

Key Points

  • Migrations track changes in Django models and apply them to the database.
  • They prevent data loss by updating the schema safely.
  • Use makemigrations to create migration files and migrate to apply them.
  • Migrations help keep code and database in sync, especially in teams.

Key Takeaways

Migrations update your database schema automatically when models change.
Always run makemigrations and migrate after modifying models.
Migrations keep your database and code synchronized safely.
They are crucial for managing database changes in team projects.