How to Squash and Merge Django migrations?

Introduction

Django Migrations are one of the main features that keep me coming back to Django for most of the projects I work on. Being able to simply define the database model in python, and then sync it with the database schema using migrations adds so much value to a project.

Unlike frameworks such as PHP’s Laravel where you have to define your own migrations, Django will automatically create a migration file as soon as we change our model. It’s like magic.

How To Squash all migrations for one app and merge it into one migration ?

For example, imagine that we have a list of the following migration files.

./foo
    ./migrations
        0001_initial.py
        0002_userprofile.py
        0003_article_user.py
        0004_auto_20190101_0123.py

In many cases, we might just want to attempt to merge all of them. We could do this by executing the following management command.

python manage.py squashmigrations <app_name> <squash_to>

0004 refer to the prefixed number of the migration files and the result of the command is that it attempts to squash all the migrations from 0001 up until 0004.

The command then generates a new file named 0001_squashed_0004_auto_<timestamp>.py.

If you want to squash only some migrations not all migrations into one migration file

you should run this command:

python manage.py squashmigrations <app_name> <squash_from> <squash_to>

You will get a confirmation message to confirm the migrations files which will be squashed.

Will squash the following migrations:
 - 0007_deliverycourier_last_notification
 - 0008_auto_20220304_1324
Do you wish to proceed? [yN] 

After confirmation:

You should commit this migration but leave the old ones in place;
the new migration will be used for new installs. Once you are sure
all instances of the codebase have applied the migrations you squashed,
you can delete them.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Select your currency
EGP Egyptian pound