Home >>Django Tutorial >Django Database Migrations

Django Database Migrations

Django Database Migrations

Migration is a way of applying the changes that we have made to a model into the database schema. Django creates a migration file inside the migration folder for every model to make the table schema and every table is mapped to the model of which migration is created.

Django provides various commands that can be used to perform the migration-related tasks:

  • makemigrations :It is used to create a migration file that contains code for the tabled schema of a model.
  • migrate : It is used to create a table according to the schema defined in the migration file.
  • sqlmigrate :It is used to show a raw SQL query of the applied migration.
  • showmigrations : It is used to list out all the migrations and their status.

Now let's see a example where we have a model and it contains the following attributes:

//models.py
	
from django.db import models  
class Employee(models.Model):  
    eid = models.CharField(max_length=20)  
    ename = models.CharField(max_length=100)  
    econtact = models.CharField(max_length=15)  
    class Meta:  
        db_table = "employee"
          

To create a migration for this model, we will use the following command:

$ python3 manage.py makemigrations  

This command will create a migration file inside the migration folder. This file will contain the code in which a Migration class is created that contains the name and fields of the employee table.

Migrations

// 0001_initial.py

from django.db import migrations, models  
class Migration(migrations.Migration):  
    initial = True  
    dependencies = [  
    ]  
    operations = [  
        migrations.CreateModel(  
            name='Employee',  
            fields=[  
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),  
                ('eid', models.CharField(max_length=20)),  
                ('ename', models.CharField(max_length=100)),  
                ('econtact', models.CharField(max_length=15)),  
            ],  
            options={  
                'db_table': 'employee',  
            },  
        ),  
    ]  

After creating a migration, we will migrate it so that it reflects the database permanently. The migrate command for this will be:

$ python3 manage.py migrate  

We can also see the raw SQL query executing behind the applied migration using the sqlmigrate app-name migration-name.

$ python3 manage.py migrate  

We will use theshowmigrations command to show the applied migrations. It will show all migrations applied to the project.

$ python3 manage.py showmigrations