Django Basic App Model - Makemigrations and Migrate
Last Updated :
21 May, 2025
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:
- makemigrations: Creates migration files based on changes made to your models.
- 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:
Similar Reads
Django Models
A Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Djangoâs ORM (Object Relational Mapper), which allows u to interact with the database in a more read
8 min read
Django ORM - Inserting, Updating & Deleting Data
Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Django Basic App Model - Makemigrations and Migrate
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 instru
4 min read
Add the slug field inside Django Model
The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
4 min read
Intermediate fields in Django - Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system:A Customer can purchase multiple Items.An Item can be
2 min read
Uploading images in Django - Python
Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, weâll walk through a
3 min read
Change Object Display Name using __str__ function - Django Models | Python
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Ob
2 min read
Custom Field Validations in Django Models
In Django, field validation is the process of ensuring that the data entered into a field meets certain criteria. Custom field validation allows us to enforce rules such as checking for specific formats, length restrictions or even more complex conditions, like validating an email to belong to a spe
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to use Django Field Choices ?
Djangoâs choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.Choices are defined as pairs: the first value is saved to the database, and the second is
2 min read