DEV Community

Cover image for How to squash migrations in Django
Miguel A. Gavilán Merino
Miguel A. Gavilán Merino

Posted on • Updated on

How to squash migrations in Django

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 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:

Enter fullscreen mode Exit fullscreen mode

We can squash all of them executing the next command:
python 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!

Top comments (0)