In this tutorial, we will explore how to manage migrations in Django. Migrations are a way for Django to propagate changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
By the end of this tutorial, you will know how to:
- Create a new migration based on changes you have made to your models.
- Apply and unapply migrations.
- Squash migrations.
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They're designed to be mostly automatic, but you'll need to know when to make migrations, when to run them, and the common problems you might run into.
When you make changes to your models, Django tracks those changes and allows you to migrate them into your database schema by creating a migration file.
For example, if you have an app called blog
and you add a new model Post
, you can create a new migration file with the following command:
python manage.py makemigrations blog
This will create a migration file in your blog/migrations
directory.
To apply the migration and thus update your database schema, you run the following command:
python manage.py migrate blog
You can also unapply a migration, which will undo the changes made to the database schema. This is done with the following command:
python manage.py migrate blog 0001
If you have a lot of migration files, you can squash them into one file with the following command:
python manage.py squashmigrations blog 0001
This will create a new migration file that incorporates all the changes from the squashed migrations.
Suppose you have a Post
model in your blog
app and you've added a new field author
. The Post
model now looks like this:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=100) # new field
To create a migration for this change, you would run:
python manage.py makemigrations blog
This will create a new file in the blog/migrations
directory, something like 0002_add_author.py
.
To apply the migration you just created, you would run:
python manage.py migrate blog
This will update your database schema to include the new author
field in your Post
model.
To unapply the migration, you would run:
python manage.py migrate blog 0001
This will undo the changes made by the 0002_add_author.py
migration and remove the author
field from your database schema.
In this tutorial, you learned how to manage migrations in Django, including how to create, apply, unapply, and squash migrations.
To continue learning about Django migrations, consider reading the official Django documentation on migrations.
Solutions to these exercises can be found by following the steps in this tutorial. For further practice, consider making more complex changes to your models and migrating those changes, or try working with a larger Django project.