DEV Community

Cover image for Django Migrations
Fahid Latheef A
Fahid Latheef A

Posted on

Django Migrations

Introduction

In the last episode, we talked about Django Architecture and settings.py file. In this episode, we'll discuss Django Migrations.

Django Migrations

Migrations are used to update the changes (to add a new field, change the name of a field, etc.) we made in the model to the database.

Django creates migration files (a Python file) inside the migration folder for each model to create the table schema, and then each table is mapped to the respective migration files. Django also keeps track of the status of migration files whether they are successfully migrated to the database.

To perform migration-related tasks, we can use these commands.

makemigrations

python manage.py makemigrations
Enter fullscreen mode Exit fullscreen mode

This is used to create migrations files in the migrations folder based on the changes we have done to the Model.

migrate

python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Based on the migrations file, this command will populate the database schema.

showmigrations

python manage.py showmigrations
Enter fullscreen mode Exit fullscreen mode

This lists all the migrations and their status. If the change is updated in the database, the status will be shown as [X] followed by the migration name.
For example:

[X] 0001_initial
[  ] 0002_auto_20210924_1740

sqlmigrate

Usage:

python manage.py sqlmigrate <app_name> <migration_name>
Enter fullscreen mode Exit fullscreen mode

This is used to display the raw SQL query of the applied migrations. For example:

python manage.py sqlmigrate users 0009_delete_profile
Enter fullscreen mode Exit fullscreen mode

will give the raw SQL query like as below

BEGIN;
DROP TABLE "users_profile" CASCADE;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

Miscellaneous Commands and Uses

  • syncdb
python manage.py migrate --run-syncdb
Enter fullscreen mode Exit fullscreen mode

This command allows us for creating tables for apps without migrations.

  • Creating and applying migration for a particular app

If we don't want to apply migrations totally, we can mention app-name to migrate specific apps.

For example:

python manage.py makemigrations blog
Enter fullscreen mode Exit fullscreen mode
python manage.py migrate blog
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)