If it did make it all the way to the database, it's obviously an IntegrityError. However, if this is happening before it makes it to the database -- say, in a save method in a Manager class -- what would be the proper exception to raise?
Example:
class MyManager(models.Manager):
def create_from_user(self, user):
try:
existing = self.get(user=user)
raise Exception("There is already an object for this user.") # more specific exception needed
except self.DoesNotExist:
# begin creating the record
Because of the nature of the record, I do not want a get_or_create type situation (I want using this method when the record already exists to be a hard error that throws an Exception).
Assuming that I put unique constraints on my table, obviously eventually an IntegrityError would be thrown but I'd rather not rely on this and instead make this explicit in the code. But I'm not sure what exception is most accurate (or if I must roll my own).
I'd say this was a ValidationError
. That's what Django throws in the form and model clean methods when it encounters a duplicate entry on a unique field.
Why not throw an IntegrityError
yourself? In a sense, your database related code has detected that an integrity problem is about to occur. There's no need to make up a different error / exception to describe something that already has a name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With