0
0
Djangoframework~5 mins

makemigrations and migrate commands in Django

Choose your learning style9 modes available
Introduction

These commands help you save and apply changes to your database structure easily.

When you add or change a model in your Django app.
When you want to create the initial database tables for your app.
When you want to update the database after changing fields or adding new ones.
When you want to share database changes with your team.
When setting up a new environment and need to create the database schema.
Syntax
Django
python manage.py makemigrations
python manage.py migrate

makemigrations creates files that describe your database changes.

migrate applies those changes to the actual database.

Examples
This command checks your models and prepares migration files for any changes.
Django
python manage.py makemigrations
This command applies all pending migrations to update your database.
Django
python manage.py migrate
This creates migration files only for the specified app.
Django
python manage.py makemigrations appname
This applies migrations up to a specific migration number for an app.
Django
python manage.py migrate appname 0001
Sample Program

This example shows a simple model for books. Running makemigrations creates a migration file describing the new table. Running migrate creates the table in the database.

Django
# models.py
from django.db import models

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

# Terminal commands
# Step 1: Create migration files
# python manage.py makemigrations

# Step 2: Apply migrations to database
# python manage.py migrate
OutputSuccess
Important Notes

Always run makemigrations after changing models to keep migrations up to date.

Run migrate to apply all migrations before running your app to avoid errors.

You can look inside migration files to see what changes will be applied.

Summary

makemigrations creates files describing database changes.

migrate applies those changes to the database.

Use these commands to keep your database structure in sync with your Django models.