python - Django : Deduce duplicate key exception from IntegrityError -
this question has answer here:
with django 1.6, exception when there's duplicate key
integrityerror: duplicate key value violates unique constraint "..." django uses integrityerror exception other types of database violations too. want handle duplicate key 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 unique error code or have parse error message. i'm trying avoid get call database ascertain violation due duplicate key.
update: should mention exception thrown psycopg2 since i'm using django postgresql.
based on comment @karthikr, found error type:
type(e.__cause__) <class 'psycopg2.integrityerror'> a little poking around showed this:
e.__cause__.pgcode '23505' my understanding is, long stick same database can check verify it's duplicate key error.
& psycopg2 doesn't change error code,
Comments
Post a Comment