Django / Django Models

Managing Migrations in Django

In this tutorial, we will learn how to manage migrations in Django. Migrations are how Django stores changes to your models and thus to your database schema.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores Django models, including defining models, relationships, and model queries.

1. Introduction

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.

Goals

  • Understand how migrations work in Django
  • Learn how to create and apply migrations
  • Learn how to reverse migrations

What You Will Learn

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.

Prerequisites

  • Basic understanding of Python.
  • Basic understanding of Django, including how to create a project and a simple app.
  • Django installed on your local machine.

2. Step-by-Step Guide

What are 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.

Creating Migrations

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.

Applying Migrations

To apply the migration and thus update your database schema, you run the following command:

python manage.py migrate blog

Unapplying Migrations

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

Squashing Migrations

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.

3. Code Examples

Example 1: Creating a Migration

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.

Example 2: Applying a Migration

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.

Example 3: Unapplying a Migration

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.

4. Summary

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.

5. Practice Exercises

  1. Create a new Django app and a simple model. Then create a migration for it.
  2. Apply the migration you just created.
  3. Add a new field to your model and create a new migration. Then apply it.
  4. Unapply the last migration you applied.
  5. Squash all your migrations into one.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Image Converter

Convert between different image formats.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help