beruic
beruic

Reputation: 5876

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?

Upvotes: 1

Views: 963

Answers (2)

Mariano Ruiz
Mariano Ruiz

Reputation: 4749

The right way is raising a CommandError('My message explaining the problem') (package django.core.management).

Migrations are executed within a command, and the difference is: if you use any other exception class, the result will be the same, but the traceback is going to be displayed in the user's terminal, making the error to look something wrong about the code, but you did raise the exception on purpose, wanting to (1) stop the code (2) rollback any change and (3) let the user know why, but there is no reason to show the traceback, so using CommandError the error is going to be shown without traceback trail, like the following, right before abort the command:

CommandError: My message explaining the problem

Upvotes: 2

QasimK
QasimK

Reputation: 425

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.

Upvotes: 2

Related Questions