If you have been working on Django based web application, you will end up having dozens of migration files. Though it doesn’t affect the application performance at all, it’ll take time to apply them all if you spinning up with new database. Sometimes having a single fresh migration file per app is desirable. In this article, we will be addressing two known methods to achive that 😎.
Official Django Documentation recommends squashing migrations.
- Squash existing migrations. Run
- Apply new squashed migration file(s). Run
- Delete old migrations, keep squashed migration(s) only.
Squashed migrations are special because they:
- have word
squashedin the filename.
- are not dependatant to previous ones.
- are marked as
initial=Truewhich indicates this is a new initial migration
replaces=[...]attribute that includes migrations merged.
Things get little complicated when you are working on real-world production application with a team of developers. You have to take an extra caution.
- Make sure to apply unapplied migrations before Squashing.
- Test on one of your co-workers local machine. This requires your team to be aligned.
- Keep all of your migrations until squashed migration file(s) got successfully applied to staging, testing, and production database. If things go wrong, you will be able to revert back.
squashmigrations command might fail and result in
CircularDependencyError which is pretty common, however, Django Documentation gives a solution to resolve it 🥳.
This method is similar to above, but you pretend you have written all models at once and have never ever had any migrations applied.
- Delete existing migration files, keep migrations folder empty with only
- Remove all records from django migrations table in database. Run
django-admin dbshelland execute
- Create new migration files. Run
- Apply new migrations with fake flag. Run
django-admin migrate --fake
Repeat the steps several times and know exactly what you are doing.
This method requires you to write SQL query and execute directly which is risky and you might accidentally drop a table/database instead 🤯.
You dont have to bother with your migrations and never touch them at all. If have hundreds of migration files and you want to clean them up, try one of the ways above. I just shared my experience with you. Happy coding👨💻!!!