0
0
Djangoframework~5 mins

Migrations concept and workflow in Django

Choose your learning style9 modes available
Introduction

Migrations help you save and apply changes to your database structure easily. They keep your database and code in sync without manual work.

When you add a new model or change an existing model in your Django app.
When you want to update the database schema after changing fields or relationships.
When you need to share database changes with your team or deploy to a server.
When you want to keep track of database changes over time safely.
When you want to rollback or undo database changes if needed.
Syntax
Django
python manage.py makemigrations
python manage.py migrate

makemigrations creates migration files based on model changes.

migrate applies those changes to the database.

Examples
This command looks at your models and creates new migration files for any changes.
Django
python manage.py makemigrations
This command applies all pending migrations to update your database schema.
Django
python manage.py migrate
This applies migrations up to a specific migration number for an app.
Django
python manage.py migrate appname 0002
This shows which migrations have been applied and which are pending.
Django
python manage.py showmigrations
Sample Program

This example shows a simple model. After creating it, you run migrations commands to create the matching table in the database.

Django
from django.db import models

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

# After saving this model, run:
# python manage.py makemigrations
# python manage.py migrate

# This creates a table for Book in the database.
OutputSuccess
Important Notes

Always run makemigrations after changing models to create migration files.

Run migrate to apply changes to your database before running your app.

Keep migration files in version control to share changes with your team.

Summary

Migrations keep your database structure in sync with your Django models.

Use makemigrations to create migration files and migrate to apply them.

Migrations help you track, share, and safely update your database schema over time.