pythondjangodjango-rest-framework

Extract details from Integrity error in Django


I'm getting integrity error from Django in below format

ForeignKeyViolation('insert or update on table "foo_bar" violates foreign key constraint "foo_obj_product_id_97ae618a_fk_designman"\nDETAIL:  Key (product_id)=(9bb7fd8c-2ed2-4a75-ab08-c749459a5097) is not present in table "foo_product".\n'

Is there any inbuilt method to extract the "details"?


Solution

  • sys module provide exc_info() method to access exception details:

    try:
        # code that raise IntegrityError
    except IntegrityError:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        print(exc_type) # <class 'django.db.utils.IntegrityError'>
        print(exc_tb.tb_lineno) # line that raised the exception
        print(exc_obj.args) # list of arguments that are displayed as exception message
    

    You can play with the returned objects and extract what you need.