Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to squash recent Django migrations?

In Django's migrations code, there's a squashmigrations command which: "Squashes the migrations for app_label up to and including migration_name down into fewer migrations, if possible."

So, if you want to squash, say, the first 5 migrations, this will help.

What's the best way to squash starting with a particular migration_name?

In a project I'm currently working on, we've added 5-10 new migration files as we've added new features. We'll deploy the whole project at once and it looks like running these individually will take too long. I'd like to squash all the migrations for this project into a single migration and test the time to run that.

like image 432
Doug Harris Avatar asked Oct 13 '16 18:10

Doug Harris


People also ask

How do I reduce the number of migrations in Django?

Delete the old migrations, dependencies, and associated functions. Run python manage.py makemigrations to create new migrations from the current models. Temporarily replace the startup logic that applies migrations to: Run the script that deletes the contents of the django_migrations table.

How do you known that the changes are migrated in Django?

Adding migrations to apps Now, run python manage.py migrate --fake-initial , and Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied.


2 Answers

python manage.py squashmigrations <appname> <squashfrom> <squashto>  python manage.py help squashmigrations 

https://docs.djangoproject.com/en/dev/topics/migrations/#migration-squashing

This will give you more granular control over which migrations to squash, and let you keep a cleaner commit history. Deleting + recreating all migrations may cause other issues such as circular dependencies depending on how models are constructed.

like image 75
A--- Avatar answered Oct 06 '22 17:10

A---


You can just delete the migration files and run makemigrations again. If you have a dev deployment that uses these, you should migrate back to the one before the first one you delete.

Also, it's probably a good idea to commit your code first, in case something goes wrong.

Also:

The slight complication with this is that if there's custom RunPython code, it won't be included in the new migration created by makemigrations

like image 31
Dan Avatar answered Oct 06 '22 16:10

Dan