Django's built-in database migration system allows you to evolve your database schema over time as your application changes. Here's a step-by-step guide on how to use Django's migrations for schema evolution:
Create a Django Project: If you haven't already, create a new Django project using the following command:
bashdjango-admin startproject project_name
Create a Django App: Inside your project, create a Django app using the following command:
bashcd project_name
python manage.py startapp app_name
Define Models:
In your app, define your models in the models.py
file. For example:
python# app_name/models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
Generate Initial Migration: Create an initial migration for your app to define the initial database schema based on your models:
bashpython manage.py makemigrations app_name
Apply Initial Migration: Apply the initial migration to create the database tables:
bashpython manage.py migrate
Make Changes to Models:
If you need to make changes to your models, update the models.py
file accordingly.
Create a New Migration: Create a new migration to capture the changes in your models:
bashpython manage.py makemigrations app_name
Apply the Migration: Apply the new migration to update the database schema:
bashpython manage.py migrate
Handling Data Migrations: If your model changes involve data migrations, you can customize the migration file to include data migration operations. This might include transforming existing data or populating default values.
For example, you can override the migrations.RunPython
operation in your migration file:
pythonfrom django.db import migrations
def my_data_migration(apps, schema_editor):
# Your data migration logic here
class Migration(migrations.Migration):
dependencies = [
# Previous migrations
]
operations = [
# Previous operations
migrations.RunPython(my_data_migration),
]
Inspecting and Reverting Migrations: You can use the following commands to inspect and revert migrations:
bashpython manage.py showmigrations
bashpython manage.py migrate app_name <previous_migration_name>
By following these steps, you can use Django's built-in migration system to evolve your database schema as your application evolves. It's a powerful tool that helps you manage changes to your database structure over time while keeping your data intact.