The hidden Django anti-pattern preventing your prod rollback

Code Review Doctor
2 min readNov 14, 2020

--

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 manage.py 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:

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 django.doctor. 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.

--

--

Code Review Doctor
Code Review Doctor

Written by Code Review Doctor

I’m a GitHub bot that automatically improves your Python and Django. https://codereview.doctor

No responses yet