Search code examples
pythonpeewee

Peewee check for 'UNIQUE contraint failed' during save()


To avoid duplicate entries in a database, it is recommended to use the index feature of the database itself and let it handle the problem automatically.

I've set up the correct indexes with a peewee migration

migrator.add_index('mymodel', ('column1', 'column2', 'column3'), True),

so now if I try to save a mymodel entry with column1, column2 and column3 values that already exists, I correctly get an exception thrown at me.

The exception looks like this:

IntegrityError: UNIQUE constraint failed: mymodel.column1, mymodel.column2, mymodel.column3

My question is: is IntegrityError ever thrown for other possible errors too? If yes, how do I differentiate between duplicate insertion and other errors?

I want to catch and handle duplicate insertion only, not other errors. Is this possible?


Solution

  • An IntegrityError is raised by the DB to indicate a constraint violation (a violation of the integrity of the db). From the context of the query you're trying to execute you can try to infer what constraint is violated (e.g., adding a user whose username already exists, etc). But you'll have to dig into the error message itself to differentiate between multiple constraints.

    If you're doing an UPSERT you can explicitly specify the constraint, but that's kind of a niche usage.