With Django 1.6, I get an exception when there's a duplicate key
IntegrityError: duplicate key value violates unique constraint "..."
Django uses IntegrityError
exception for other types of database violations too. I want to handle the duplicate key
as a special case i.e.
try:
model = MyModel(name='xyz')
model.save()
except MyModal.IntegrityError:
if exception_due_to_duplicate_key:
do_something()
except:
do_something_else()
Is there a unique error code for that or will I have to parse the error message. I'm trying to avoid get
call to database to ascertain that violation is due to a duplicate key.
Update: I should mention that exception is thrown by psycopg2
since I'm using Django with PostgreSQL.
Based on the comment from @karthikr, I found the error type:
type(e.__cause__)
<class 'psycopg2.IntegrityError'>
A little poking around showed this:
e.__cause__.pgcode
'23505'
My understanding is, as long as I stick with the same database I can check this to verify that it's a duplicate key error.
& psycopg2
doesn't change the error code,
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