Model.objects.get_or_create() try/except is slightly yet insideously broken
|Reported by:||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.1|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
What is wrong with this code:
except self.model.DoesNotExist: raise e
That's right, e is not defined. But what if e is previously defined in a surrounding except block? Then we will be raising the previous exception, not the current one. That's exactly what is happening in
get_or_create(), and caused me some consternation as I was getting a "PRIMARY_KEY must be unique" exception, even though the real exception was something else.
Patch, in all its three character glory, is included.