Django Database Migrations

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

Django provides the various commands that are used to perform migration related tasks. After creating a model, we can use these commands.

  • makemigrations : It is used to create a migration file that contains code for the tabled schema of a model.
  • migrate : It creates 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 lists out all the migrations and their status.

Suppose, we have a model as given below and contains the following attributes.

Model

//models.py

To create a migration for this model, use the following command. It will create a migration file inside the migration folder.

Django makemigrations

This migration file contains the code in which a Migration class is created that contains the name and fields of employee table.

Migrations

// 0001_initial.py

After creating a migration, migrate it so that it reflects the database permanently. The migrate command is given below.

Django migrate

Apart from creating a migration, we can see raw SQL query executing behind the applied migration. The sqlmigrate app-name migration-name is used to get raw SQL query. See an example.

Django migrate 1

And showmigrations command is used to show applied migrations. See the example.

If no app-name is provided, it shows all migrations applied to the project.

Django showmigrations

We can get app-specific migrations by specifying app-name, see the example.

Django showmigrations myapp
Next TopicDjango Middleware




Contact US

Email:[email protected]

Database Migrations
10/30