Missing reverse migration

It's good to, as a minimum, specify noop in RunPython so the migration can be skipped when going backwards, and even better to specify a function that undoes the migration.

The code in forwards mutates the data, but in order to undo the change then reverse_code is needed.

If reverse_code is missing then when an attempt is made to undo the migration then Django will raise IrreversibleError.

This is a problem because it prevents rolling back the state of the database, which may be needed if a bug is detected after a production deployment and the last good version of the app needs deploying back to production. Without reverse_code, the state of the database will be out of step with the app code.

So in practice, do this


# 0006_populate_has_chickens.py
from django.db import migrations

def forwards(apps, schema_editor):
    # code that mutates the data forwards
    ...

def backwards(apps, schema_editor):
    # code that undoes the mutations from forwards
    ...

class Migration(migrations.Migration):
    dependencies = [("cases", "0005_auto_does_have_chickens.py")]
    operations = [migrations.RunPython(forwards, backwards)]



Instead of this


# 0006_populate_has_chickens.py
from django.db import migrations

def forwards(apps, schema_editor):
    # code that mutates the data forwards
    ...

class Migration(migrations.Migration):
    dependencies = [("cases", "0005_auto_does_have_chickens.py")]
    operations = [migrations.RunPython(forwards)]

Are you affected by this? Audit your codebase in seconds to find out.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code missing-reverse-migration in your pyproject.toml file.

Read more about configuring Django Doctor.