How to create and apply migrations in Django



Image not found!!

In Django, migrations are used to manage changes to your database schema over time. They allow you to propagate changes made to your models (such as adding a new field or modifying an existing one) to your database in a structured and organized way. Here's a step-by-step guide on how to create and apply migrations in Django:

1. Create a Django Project

If you don't have a Django project yet, you can create one using the following command:

bash
django-admin startproject yourprojectname

2. Create a Django App

Navigate to your project folder and create a Django app using the following command:

bash
python manage.py startapp yourappname

3. Define Models

Edit the models.py file in your app to define your models. For example:

python
# yourappname/models.py from django.db import models class YourModel(models.Model): name = models.CharField(max_length=255) age = models.IntegerField()

4. Create Initial Migration

Run the following commands to create an initial migration:

bash
python manage.py makemigrations

This command analyzes your models and creates a set of migration files in the migrations directory of your app.

5. Apply Migrations

Apply the migrations to the database using the following command:

bash
python manage.py migrate

This command executes the SQL statements defined in the migration files to update the database schema.

6. Make Model Changes

If you make changes to your models, update the models.py file accordingly.

7. Create and Apply New Migrations

Generate new migrations based on your model changes:

bash
python manage.py makemigrations

Apply the new migrations:

bash
python manage.py migrate

Additional Migration Commands

  • To view the list of migrations and their status:

    bash
    python manage.py showmigrations
  • To roll back migrations:

    bash
    python manage.py migrate yourappname <migration_name>
  • To fake migrations without running them:

    bash
    python manage.py migrate --fake

These are the basic steps for creating and applying migrations in Django. Make sure to consult the Django documentation for more advanced use cases and additional migration options.