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.
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.pyclass 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.
Practice
(1/5)
1. What is the primary purpose of running python manage.py migrate in a Django production environment?
easy
A. To create new migration files based on model changes
B. To apply database schema changes defined in migration files
C. To start the Django development server
D. To reset the database to its initial state
Solution
Step 1: Understand the migrate command
The migrate command applies changes to the database schema based on migration files already created.
Step 2: Differentiate from makemigrations
makemigrations creates migration files, but migrate applies them to the database.
Final Answer:
To apply database schema changes defined in migration files -> Option B