Welcome to our Django Migrations tutorial! In this lesson, we'll explore what migrations are, why they're essential for Django projects, and how to create, apply, and unapply migrations. Let's get started!
In Django, migrations are files that describe the current state of your database schema, including tables, columns, and relationships. They help manage database changes as you develop your application.
Migrations are essential for several reasons:
Let's create a new Django project and an app called blog to illustrate migrations in action.
django-admin startproject mysite
cd mysite
blog:python manage.py startapp blog
blog/models.py file and define a simple Post model:from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField('date published')python manage.py makemigrations blog
After creating the initial migration, we need to apply it to our database:
python manage.py migrate
Now, Django has created the Post table in our database.
Let's make a change to our Post model:
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField('date published')
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)We've added an author field to the Post model. To create a new migration that reflects these changes, run:
python manage.py makemigrations blog
After creating the updated migration, we can apply it to our database:
python manage.py migrate
Now, the Post table has been updated with the new author field.
You can roll back a migration by using the migrate command with the --fake option. Let's roll back to the previous state of the Post model:
python manage.py migrate blog zero
If you want to roll back to a previous state of the `Post` model, what command should you use?
That's it for our Migrations Introduction lesson! In the next lesson, we'll dive deeper into managing migrations, exploring advanced topics like managing multiple databases and customizing migrations. Stay tuned! π―