Understand A to Z about migrations in Django
What is a migration?
Movement from one part of something to another.
What is Migration in Django?
Django’s way of propagating changes you make to your models into your database schema
Why migrations?
They help developers plan, validate, and safely apply schema changes to their environments without confusions.
How are migrations designed in django?
Before understanding migrations lets understand the structure of django
As the above figure represents the hierarchy in Django, i.e.,
Every model is under an application and every application is under a project.
Each Model will be creating a migration (.py) file that is responsible to create table in the Database
Let’s Discuss about the creation of migration file later.
Suppose you have to create a backend system to store employee details of a company
Requirements:
These below fields needs to be saved in the database:
- employee_id
- first_name
- last_name
- age
- gender
Solution:
Lets see how can we achieve this using Django
Switch to the virtual environment created in your system using
source <env>/bin/activate
Create a django project
As you can see it creates one more file called manage.py which is Django’s command-line utility for administrative tasks like migration, runserver, createsuperuser (etc.)
Create a django application inside django project folder
Once the application is created lets see what is inside it.
It has migrations folder which contains empty __init__.py file
Before creating the models lets run showmigrations command to see the migrations that needs to be applied to the database
As shown in the above diagram these apps admin, auth,contenttypes, sessions need to be migrated and get converted as tables. Along with columns creations/updations as shown in the migration files
Since the migrations were done by default after running makemigrations it detects no change we need to migrate them to the database
Lets run Migrate command which creates Database tables and columns in their respective table
These migration files will create the tables in the database according to the specifications mentioned by Django.
Below are the default django tables created after migrating
As highlighted there is a table called django_migrations which stores the complete details of the migrations made in your project
This is the data in django_migrations which contains id(autofill), app(application name), name(migration command name), applied(timestamp of the migration done)
These are default tables that get created for every django project. Now let’s see how to create custom tables in Django.
Earlier, we had a requirement of creating employee database
- employee_id
- first_name
- last_name
- age
- gender
To create the table we need to create a class called EmployeeData and inherit Model from models (models.Model)
And define the class variables in it, which will be created as columns in the table
Mention the data type and data length that needs to be stored in the respective columns according to the specifications
Now to apply these migrations in to your database we need to create migration files in our system. Before that we need to mention our application name in INSTALLED_APPS= [ ] in settings.py
Now switch back to the terminal to create the migrations of the django application by mentioning its name in the command
python3 manage.py makemigrations datastore
After running the makemigrations command as you can see the response. There is a file being created in the folder migrations of application datastore named 0001_initial.py.
Now, Let’s inspect what’s being created in this python file
This has created a default class called migration, inheriting from django.db.migrations.Migration which is the base class for all the migrations.
What does these 3 variables initial, dependencies, operations actually mean and why are they defined?
- initial
Since it is the initial migration of the application datastore the variable initial is marked as True
2. dependencies
This defines a list of tuples which defines the other migrations that need to be run before running the migration file.
Since this is our initial migration to the application there are no dependent migrations from other migrations.
3. operations
This defines the list of auto-generated operations to be applied during this migration process (in sequence).In our case there is an operation that needs to be performed i.e creation of model with specified fields and field specifications
‘id’ is the Auto generated field that gets created during the creation of every entry (Employee) in the Database.
verbose_name is the human understandable name set by the django if not given in the models.py
Now let’s try to run the server
As it is mentioned in the response of the command we have one migration that is created in the folder but not applied to the database.
Now let’s apply the migration to the database using
python3 manage.py migrate
This migration will be saved in django_migrations and using it the migration will be applied in the Database
Let’s check django_migrations table
As you can see the migration 0001_initial of datastore application was saved in the table with id 19 on 03 Apr 2023, 07:44 UTC Time
There is a table called “datastore_emplyeedata” created in the DB
Lets rename the table name in models.py and migrate again and see what happens
As it is a code change in models.py, we need to run makemigrations command to reflect in the DB as it creates one more migration file in the migrations folder
The migration was created with the name 0002_rename_emplyeedata_employeedata.py
Now, let’s inspect the migration file to know more about it
Since, it is not an initial migration initial variable is not defined in the class
And the dependencies of this migration file is 0001_initial.py file of datastore application.
Operations defined in this file is Renamemodel which takes two params i.e old_name and new_name
Lets migrate this file so that we can see this in the database
This has created a new entry in the django_migrations with id 20
The changes are reflected in the Database
I would suggest you to go through every migration file created after running the makemigrations command.
Important: If there is a conflict in creation of migration files in your project instead of merging the migrations or dropping the Database we can just delete the migration of the particular app and run the makemigrations command again.
Conclusion: This brings to the conclusion of django migrations.Hope I have explained the django migrations in detail and cleared the confusions if any in this article. Stay tuned for more articles in the near future.