0
0
Djangoframework~7 mins

Database migration in production in Django

Choose your learning style9 modes available
Introduction

Database migration in production helps update your app's database safely without losing data. It changes the database structure to match your new code.

When adding a new feature that needs new database tables or columns.
When fixing bugs that require changing database fields.
When removing unused database columns or tables.
When updating data types or constraints in the database.
When deploying a new version of your app that changes how data is stored.
Syntax
Django
python manage.py makemigrations
python manage.py migrate
Use makemigrations to create migration files based on model changes.
Use migrate to apply those changes to the database.
Examples
Basic commands to create and apply migrations.
Django
python manage.py makemigrations
python manage.py migrate
Apply a specific migration number for an app.
Django
python manage.py migrate app_name 0002
See which migrations have been applied.
Django
python manage.py showmigrations
Sample Program

This example shows adding a new field stock to an existing model. Running migrations updates the database safely.

Django
from django.db import models

# models.py
class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)

# After adding a new field:
class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    stock = models.IntegerField(default=0)

# Commands to run in terminal:
# python manage.py makemigrations
# python manage.py migrate

# This will add the 'stock' column to the Product table without losing existing data.
OutputSuccess
Important Notes

Always back up your production database before running migrations.

Test migrations on a staging environment first to avoid surprises.

Use --fake option carefully if you need to mark migrations as applied without running them.

Summary

Database migrations update your database structure safely.

Use makemigrations to create and migrate to apply changes.

Always test and back up before migrating in production.