Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct exception when trying to create a Django record when only one record is allowed

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).

like image 759
Jordan Reiter Avatar asked Dec 26 '22 22:12

Jordan Reiter


2 Answers

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.

like image 138
Daniel Roseman Avatar answered May 20 '23 17:05

Daniel Roseman


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.

like image 36
Simeon Visser Avatar answered May 20 '23 19:05

Simeon Visser