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.
Suppose, we have a model as given below and contains the following attributes.
To create a migration for this model, use the following command. It will create a migration file inside the migration folder.
This migration file contains the code in which a Migration class is created that contains the name and fields of employee table.
After creating a migration, migrate it so that it reflects the database permanently. The migrate command is given below.
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.
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.
We can get app-specific migrations by specifying app-name, see the example.