Search code examples
pythondjangodjango-migrations

How to abort Django data migration?


I have a datamigration I actually want to roll back if certain condition happen.

I know that migrations are automatically enclosed in a transaction, so I am safe just raising an exception, and then trust all changes to be rolled back. But which exception should I raise to abort my Django data migration? Should I write my own exception, or am I fine with raise Exception('My message explaining the problem')? What is best practice?


Solution

  • A custom exception will give a slightly prettier message. On the other hand, migrations are usually one-off with basically no code dependencies with each other or the rest of the project, meaning you cannot reuse exception classes to ensure that each migration stands alone. The only purpose of any exception here is to provide immediate feedback since it will not be caught by anything (except possibly error logging in production environments... Where it really shouldn't be failing).

    I think the disadvantages outweigh the advantages - just raise a plain one-off Exception.