How it works...

Django migrations are instruction files for the database migration mechanism. The instruction files inform us on which database tables to create or remove, which fields to add or remove, and which data to insert, update, or delete.

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 programmed 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:

(myproject_env)$ python3 manage.py migrate demo_app 0002  

This does require that each migration has both a forward and a backward action. Ideally, the backward action would exactly undo the changes made by the forward action. However, in some cases such a change would be unrecoverable, such as when the forward action removed a column from the schema, because it would destroy 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.

If you want to undo all of the migrations for a specific app, you can do so by using the following command:

(myproject_env)$ python3 manage.py migrate demo_app zero
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 development and public website environments.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.125