Django: Throw duplicate key exception from IntegrityError

With Django 1.6, I get an exception when there is a duplicate key

IntegrityError: duplicate key value violates unique constraint "..."

Django uses an exception IntegrityErrorfor other types of database violations. I want to handle duplicate keyas 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 this, or will I have to parse the error message. I try to avoid calling getthe database to make sure that the violation is associated with a duplicate key.

Refresh . I should mention that the exception is thrown psycopg2as I use Django with PostgreSQL.

+4
source share
1 answer

@karthikr, :

type(e.__cause__)
<class 'psycopg2.IntegrityError'>

:

e.__cause__.pgcode
'23505'

, , , , , .

& psycopg2 ,

+4

All Articles