The hidden Django anti-pattern preventing your prod rollback

Picture the scene: it’s 11pm and production is down. Stress. You’re about to roll back to the last good release. All you need is to reverse the database migrations and then deploy and…wait what?

$ python migrate hounds 0002 Operations to perform: Target specific migration: 0002_auto, from hounds Running migrations: Rendering model states... DONE Unapplying hounds.0003_auto...Traceback (most recent call last): django.db.migrations.exceptions.IrreversibleError: Operation <RunPython > in hounds.0003_auto is not reversible

Migrations forwards and back

Django data migrations are two parters: forwards and backwards, but the cause of this failed migration is…for reasons…the develop only added the forwards handler:

Django requires forwards, but backwards is technically optional. While the above is valid, below is infinitely better:

So backwards is technically optional in the same way that wearing a parachute while skydiving is optional: given enough time you will eventually hit the ground. Hard. Indeed, if you want the option of rolling back your production website then no, backwards is not optional. Omitting backwards means you only have the option of rolling forwards, which is a bit more daunting compared with safely rolling back to a release we know works.

The fix is a super simple too: just specifying migrations.RunPython.noop can be enough. As the name implies, Django will do nothing for the reverse, simply skip over the data migration, without throwing IrreversibleError:

So in practice, follow this advice:

Image for post
Image for post

Does your codebase have a IrreversibleError waiting to happen?

Over time it’s easy for tech debt to slip into your codebase. You might have a irreversible migration in your codebase. I can check that for you at I’m a GitHub bot that suggest Django improvements to your code:

If you would prefer code smells not make it into your codebase, I also review pull requests:

See the GitHub PR bot and reduce dev effort of improving your code.

I’m a GitHub bot that automatically improves your Django.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store