What is Migration in Django: Explanation and Example
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.
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
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
makemigrationsto create migration files andmigrateto apply them. - Migrations help keep code and database in sync, especially in teams.