Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge consecutive database migrations in django 1.9+?

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).. ?

like image 444
Pranjal Mittal Avatar asked Apr 09 '16 19:04

Pranjal Mittal


People also ask

How do I merge two migrations in Django?

execute python manage.py makemigrations –merge and the migrations will automatically be merged; you will see that a new migration, 0004_merge.py, is created inside the migrations folder. execute python manage.py migrate.

What is difference between migrate and Makemigrations in Django?

makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.


2 Answers

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

like image 62
Abhinav Avatar answered Sep 28 '22 11:09

Abhinav


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

like image 34
doniyor Avatar answered Sep 28 '22 13:09

doniyor