Django Migrations

Migrations are used to make changes to the models inside of the database for Django projects. Examples are adding a field, deleting a field, altering the type of a field or deleting a model. The system is designed to be mostly automatic, however there can be some issues. Migrations can be considered as a vcs for the database. In most cases, the initial database doesn’t contain the same fields and maybe even models as the finished database. Migrations are used to adjust the database and keep track of changes.

They should be created only once but applied everywhere. This means if developer a creates a new migration, he should make it available to other contributors, who then should apply them, for example developer b & c. The same applies for the patches made by either developer b or c. Developer a needs to apply those.

Structure

This section documents the structure of Django migrations.

Commands

Django provides several commands for managing database migrations. The commands are given are:

Finding Migrations

The migration files live in the migrations/ directory for each app. They should be included into the vcs that the project uses.

Usage

This section describes on how to create and use migrations for Django projects.

Create a new migration

To create a new migration, first change some models. After this is done, run:

$ python manage.py makemigrations

This will create a migration inside of the migrations/ directory for the corresponding application. The migration will have an auto-generated name that should be pretty accurate out of the box.

NOTE: This command will only create a migration. This migration also needs to be applied.

Applying a migration

To apply a new migration, run:

$ python manage.py migrate

This will apply any migrations that were pending.

Roll back a migration

To roll back (reverse) a migration, it is first needed to get the version that should be reverted to. Usually, migrations have some sort of number, for example books.0002_auto. Here 0002 is the number. To roll back to this version, run:

$ python manage.py migrate books 0002