从 Django 中的完整性错误中提取详细信息

时间:2021-07-01 14:30:34

标签: python django django-rest-framework

我从 Django 收到以下格式的完整性错误

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'

是否有任何内置方法可以提取“细节”?

1 个答案:

答案 0 :(得分:0)

sys 模块提供 exc_info() 方法来访问异常详细信息:

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

您可以使用返回的对象并提取您需要的内容。