loading...
Wealize

How to squash migrations in Django

miangame profile image Miguel A. Gavilán Merino Updated on ・1 min read

Today, when I was programming in a project with DRF, I had to create a new app with its respective model.
While I was creating my model, I had to make several changes (add fields, rename fields ...) so several migration files were also generated.
This can generate problems in the future because if for each change in our model a migration file is create, we can have a lot of migration files.

Django comes with a lot of different management commands that can be executed through the manage.py file that brings a lot of utilities.

The squashmigrations is one of these commands that can help us achieve just what we're looking for. It allows us to squash multiple migration files into a single one.
 
For example, if we have the following migration files:

./foo
    ./migrations
        0001_initial.py
        0002_project.py
        0003_article_project.py
        0004_auto_20200223_0123.py

We can squash all of them executing the next command:
python manage.py squashmigrations <our_app> 0004

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

And if you open this file, you can see:

  • This file is marked as initial=True , meaning this is the new initial migration for your application.
  • A new attribute named replaces=[] and added to the Migration class with a list of strings that represent the file names of all the migrations that were squashed.

Alt img

Thanks for reading me!

Posted on by:

miangame profile

Miguel A. Gavilán Merino

@miangame

Web developer at The Neon Project · I am a hard worker, charismatic and a little perfectionist. I never think that something is good enough.

Wealize

Unlock tomorrow. We build digital products. We solve complex problems that drive the change needed to thrive in today’s world. #cognitiveservices #blockchain

Discussion

pic
Editor guide