Update migrations while you work on Django models
by Elias Hernandis • Published Feb. 27, 2023 • Tagged tips, django, news
Django version 4.2 is coming this april and it includes lots of new goodies. I'm particularly excited about the support for Psycopg3 since it's probably one of the last steps that must be taken before the ORM can be made asynchronous in Django 5.
Django 4.2 includes some enhancements and lots of fixes which make it an excellent Long Term Support release. I've been testing the first alpha and beta versions over the last few weeks and have found the
--update flag to the
makemigrations management command very useful when making changes to the model.
Basically it works like this:
- You make changes to model classes (adding, changing or removing models or fields).
- You generate a new migration with
makemigrationsand apply it with
- You realise you've made a mistake or just want to make a change.
- You can roll back the last migration with
migrate <app_name> <last_migration_number>, make the change to the model and run
makemigrations --updateagain. This will update the latest migration with the new changes.
In the past, what I would do is go find the last migration, roll it back, delete it and then generate a new one. The
--update flag only works if the last migration is not applied, so you'll need to remember to roll it back.
I know this only saves you from deleting the file but frankly going to look for it and removing it was my least favorite step. Also, since it checks that the last migration has been un-applied, it saves you from messing things up by deleting the last migration before migrating back.