Search code examples
djangomigrationdatabase-migration

What is the concrete purpose of reverting migrations in Django, and is it safe to work without?


In our Django project, we already generally implemented the reverse_func in order to be able to roll-back migrations.

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]

We do it because some team member did it with previous projects, but we never really questioned the need for that.

However with the time, it seems that we never use the rollback mechanism.

Our DB is a volume of a Docker container. When we switch on a different branch, we generally replace the volume with a precedent dev version, so that we reapply only the latest migrations.

My question is therefore: Did we mistunderstood the purpose of the reverse_func ? - What is the purpose for it in dev ? - What is the purpose for it in prod ?

And is it safe to work without them ?


Solution

  • in development environment reverse_func is not very important, If something goes wrong you can simply drop the whole db and recreate it again

    but for production environment it will help you return db back to a working state after a buggy release

    after running forwards_func in production env you may change your db and may find out it was a bad change and your site doesn't work properly any more. note that there might be some new data in your db so if you use backup you might lose these data

    in given scenario having a reverse_func can be very helpful, your reverse_func will return db to previous working state and you can simply redeploy previous version of your software

    note that sometimes reverse_func can be an empty function. it's just to tell django that this migration is reversible

    you don't always use a reverse_func but if something goes wrong (even once a year) you can see the importance of writing it