【问题标题】:getting the IntegrityError Message in Django view在 Django 视图中获取 IntegrityError 消息
【发布时间】:2020-05-13 15:59:55
【问题描述】:

我有一个包含 6 个约束的复杂模型,我想在后请求失败时向用户发送一条约束失败的消息。

 class testView(APIView):
    @staticmethod
    def post(request):
         serializer = testSerializer(data=request.data)

         if not serializer.is_valid():
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

         try:
             testModel.objects.create(
                 # all the data
             )
             return testView.get(request)
         except IntegrityError:
             return Response(status=status.HTTP_403_FORBIDDEN)

调用了异常,但我找不到在IntegrityErrorclass 中失败的特定约束。

有没有办法将特定的约束返回给用户?

(我使用 django 3.0.2 和 Postgresql)

【问题讨论】:

    标签: django python-3.x postgresql django-models


    【解决方案1】:

    exception获取实际的错误信息

    except IntegrityError as e:
        error_message = e.__cause__
    

    根据 PEP 3134,__cause__ 属性设置为原始 (底层)数据库异常,允许访问任何额外的 提供的信息。

    【讨论】:

    • 如果我这样做我得到这个错误:AttributeError: type object 'IntegrityError' has no attribute 'message'你自己试过了吗?
    • 这取决于 python/django 的版本,抱歉粘贴了旧版本,现在它在 args[0] 中,或者按照 PEP 3134 仅使用 _cause_
    • 如果您要检查__cause__ 中的子字符串,则需要对其进行字符串化,因此可以使用error_message = str(e.__cause__)。但我认为error_message = e.args[0] 更干净。
    • e.args[0] 在没有异常消息的情况下可能会引发索引错误,坦率地说,我没有针对此用例发生的特定示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多