Django 中的 get_object_or_404 快捷函数在遇到异常时会给出一个非常好的错误消息,格式如下:
'No %s matches the given query.' % queryset.model._meta.object_name)
但是,在基于 DRF 3.X 类的 View 中使用它时,最终的 404 响应数据具有非常精简的版本,如下所示:
{"detail": "Not found."}
很明显,DRF 消息非常通用,没有关于模型名称的信息。我假设 DRF NotFound 异常类定义了 here将消息剥离到当前的最低限度。
尽管在基于 DRF 类的 View 中使用了 Django 返回的原始错误消息,但我如何才能得到它?
最佳答案
APIView
的默认异常处理程序类由 get_exception_handler
决定方法。即,
def get_exception_handler(self):
"""
Returns the exception handler that this view uses.
"""
return self.settings.EXCEPTION_HANDLER
换句话说,APIView
类默认使用的处理函数是 rest_framework.views.exception_handler
(在 default settings
上指定)。
根据 DRF 文档,
By default DRF handle the REST framework
APIException
, and alsoDjango's built-inHttp404
andPermissionDenied
exceptions.
由于在这种情况下您只想为 Http404
自定义错误消息,因此您可以像这样创建自己的处理程序。
即,
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now overide the error message.
if response is not None and isinstance(exc, Http404):
# set the custom message data on response object
response.data['detail'] = exc.args[0] # exc.args[0] will have the message text,
return response
然后将此自定义处理程序放入您的项目设置中。
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
注意:此解决方案未经测试。
关于python - Django Rest 框架基于类的 View 中的 Django 快捷方式 get_object_or_404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53149680/