19

Migrations allow transforming from one database schema to another while maintaining current data in the database. Django allows creating migrations using the command python manage.py makemigrations

Each time makemigrations is run a new migration file 000n.. is added based on the changes detected in the models.py file.

Sometimes after making small changes to models.py, I want to run makemigrations but do not want a new migration to be created because the previous migrations haven't been used yet which allows them to be merged together, primarily because running each migration in production can take a lot of time when there is a lot of data in the database so merging migrations before hand may be preferable.

Is there a way to allow a new migration 000n.. to be merged with an existing migration 000(n-1).. ?

Pranjal Mittal
  • 10,772
  • 18
  • 74
  • 99

2 Answers2

20

The command you are looking for is squashmigrations. It will merge all the unapplied migrations of a given app into a single file.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Abhinav
  • 622
  • 6
  • 15
  • Use case for squash - I made a model change and the migration went fine, locally. On another server/environment, it threw an error. I made a second model change (to fix the error) and that was fine when applied locally. In the other environment, I can't apply the fix (the second migration) because the first one won't ever go through. If I can combine them together, it will succeed – s g Feb 14 '19 at 00:56
1

I want to run makemigrations but do not want a new migration to be created because the previous migrations haven't been used yet

This is not a problem, Django runs migrations from top to bottom, meaning: your latest migration file will wait until other previous migration files are ran.

because running each migration in production can take a lot of time when there is a lot of data in the database

How much data do you have in the database? If really much, then you must already have replications and redundant db servers. In this case, switch the reads and writes to one, say slave server, run the migrations in the master. and then switch the traffic back to master, and before that make sure that the lag between them is 0 and new schema is replicated properly among them

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • 1
    I didn't frame the question so well (reworded it now). I know that migrations are applied in sequence. What I was trying to say was that if 2 migrations haven't been applied yet then there may be some advantage in merging them together before hand and then applying them, rather than running them one after the other. 2nd part of this answer is interesting! – Pranjal Mittal Apr 09 '16 at 20:26