Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : Deduce duplicate key exception from IntegrityError [duplicate]

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.

like image 754
user Avatar asked Aug 18 '14 16:08

user


1 Answers

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,

like image 190
user Avatar answered Sep 22 '22 18:09

user