How to use Django's built-in database migrations for schema evolution



Image not found!!

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:

  1. Create a Django Project: If you haven't already, create a new Django project using the following command:

    bash
    django-admin startproject project_name
  2. Create a Django App: Inside your project, create a Django app using the following command:

    bash
    cd project_name python manage.py startapp app_name
  3. 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()
  4. Generate Initial Migration: Create an initial migration for your app to define the initial database schema based on your models:

    bash
    python manage.py makemigrations app_name
  5. Apply Initial Migration: Apply the initial migration to create the database tables:

    bash
    python manage.py migrate
  6. Make Changes to Models: If you need to make changes to your models, update the models.py file accordingly.

  7. Create a New Migration: Create a new migration to capture the changes in your models:

    bash
    python manage.py makemigrations app_name
  8. Apply the Migration: Apply the new migration to update the database schema:

    bash
    python manage.py migrate
  9. 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:

    python
    from 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), ]
  10. Inspecting and Reverting Migrations: You can use the following commands to inspect and revert migrations:

    • To see the list of applied migrations:
      bash
      python manage.py showmigrations
    • To revert the last migration:
      bash
      python 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.