Django migrations are instruction files for the database migration mechanism. The instruction files inform us about which database tables to create or remove, which fields to add or remove, and which data to insert, update, or delete. Also they define which migrations are dependent on which other migrations.
There are two types of migrations in Django. One is schema migration, and the other is data migration. Schema migration should be created when you add new models, or add or remove fields. Data migration should be used when you want to fill the database with some values or massively delete values from the database. Data migrations should be created by using a command in the command-line tool, and then coded in the migration file.
The migrations for each app are saved in their migrations directories. The first migration will usually be called 0001_initial.py, and the other migrations in our example app will be called 0002_subtitle_added.py and 0003_populate_subtitle.py. Each migration gets a number prefix that is automatically incremented. For each migration that is executed, there is an entry that is saved in the django_migrations database table.
It is possible to migrate back and forth by specifying the number of the migration to which we want to migrate, as shown in the following command:
(env)$ python manage.py migrate ideas 0002
To unmigrate all migrations of the app including the initial migration, run the following:
(env)$ python manage.py migrate ideas zero
Unmigrating requires each migration to have both a forward and a backward action. Ideally, the backward action would undo exactly the changes made by the forward action. However, in some cases such a change would be unrecoverable, such as when the forward action has removed a column from the schema, because it will have destroyed data. In such a case, the backward action might restore the schema, but the data would remain lost forever, or else there might not be a backward action at all.
Do not commit your migrations to version control until you have tested the forward and backward migration process and you are sure that they will work well in other developments and public website environments.