Open In App

Django Basic App Model - Makemigrations and Migrate

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.

What are Migrations in Django?

Migrations are files that store instructions about how to modify the database schema. These files help ensure that the database is in sync with the models defined in your Django project. Whenever you make changes to your models—such as adding, modifying, or deleting fields—Django uses migrations to apply these changes to the database.

Two main commands related to migrations in Django:

  1. makemigrations: Creates migration files based on changes made to your models.
  2. migrate: Applies the generated migration files to the database.

Step-by-Step Guide to Migrations in Django

Step 1: Understanding the makemigrations Command

The makemigrations command in Django is used to generate migration files based on changes made to your models. A migration file contains Python code that describes changes to the database schema, such as creating new tables, adding fields, or altering existing fields.

How It Works:

  • When you run python manage.py makemigrations, Django checks for any changes in your models and generates migration files inside the migrations/ directory of your app.
  • These migration files are automatically numbered (e.g., 0001_initial.py, 0002_auto_...) and represent the incremental changes made to the database schema.

Example:

If you add a new field to an existing model, running makemigrations will generate a migration file describing the change.

python manage.py makemigrations

Step 2: Understanding the migrate Command

After creating migration files using makemigrations, you need to apply these changes to your database using the migrate command. This command reads all the migration files and applies the necessary database changes.

How It Works:

  • The migrate command looks at the migration files generated by makemigrations and applies the changes in the correct order. It handles creating tables, modifying columns, adding indexes, and performing any other database-related operations.
  • It ensures that dependencies between migrations are respected, so migrations are applied in the right sequence.

Example:

python manage.py migrate

After running this command, Django will update the database schema to reflect the changes described in the migration files.

Creating a Basic Django App with Migrations

Now, let’s walk through an example where we create a basic Django app, define a model, and use migrations to update the database.

Step 1: Start a New Django Project

In your terminal, navigate to the directory where you want to create your Django project and run the following command:

django-admin startproject geeksforgeeks
cd geeksforgeeks

Step 2: Create a New App

To keep the project modular, create a new app called geeks:

python manage.py startapp geeks

Step 3: Register the App in settings.py

After creating the app, you need to register it in the INSTALLED_APPS section of geeksforgeeks/settings.py:

INSTALLED_APPS = [
...
'geeks', # Register the app here
]

Step 4: Define a Model in the geeks App

Open geeks/models.py and define a simple model for our application. In this case, let's create a GeeksModel with a name and description field.

Python
from django.db import models

class GeeksModel(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Step 5: Create Migration Files

Now, let’s generate migration files for our new model:

python manage.py makemigrations

Django will create a migration file (e.g., 0001_initial.py) that includes the instructions to create the GeeksModel table in the database.

Step 6: Apply the Migrations

To apply the migration and create the table in the database, run the following command:

python manage.py migrate

After you run makemigrations and migrate a new table would have been created in database. You can check it from geeks -> makemigrations -> 0001_initial.py.

Migration Files Explained

Once you run makemigrations, Django generates migration files that describe the changes made to the database schema. For example, the migration file 0001_initial.py for the GeeksModel looks like this:

Python
from django.db import migrations, models

class Migration(migrations.Migration):
    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='GeeksModel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('description', models.TextField()),
            ],
        ),
    ]

This file includes:

  • Operations: The list of changes to be applied (e.g., creating the GeeksModel table).
  • Dependencies: If the migration depends on other migrations, they would be listed here. In this case, there are no dependencies for the initial migration.

Read Next:


Next Article
Practice Tags :

Similar Reads