0

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?

beruic
  • 5,517
  • 3
  • 35
  • 59
  • Keep in mind, some kinds of migrations, like creating a new model, queue up post-migration actions, like creating ContentTypes and Permissions, that run after all outstanding migrations run (or after the specified set of migrations run if running only a specific subset of migrations). If one migration queues post-migration actions, and then a later migration raises an error, such post-migration actions will never run. I don't have documentation for this, but I at least observe it to happen in a particular Django 4.2.4 project. – David Winiecki Aug 18 '23 at 19:49

1 Answers1

2

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.

QasimK
  • 440
  • 3
  • 11