Django rest framework 将Validationerror转换为序列化程序。Django rest框架中的Validationerror
我有以下问题。 我有一个模型级验证,用于检查每次保存时的数据一致性。 在序列化程序中,如果此模型级验证有效,则会生成带有回溯的Django rest framework 将Validationerror转换为序列化程序。Django rest框架中的Validationerror,django-rest-framework,Django Rest Framework,我有以下问题。 我有一个模型级验证,用于检查每次保存时的数据一致性。 在序列化程序中,如果此模型级验证有效,则会生成带有回溯的服务器错误500,而序列化程序中的序列化程序.Validationerror会生成漂亮且干净的400错误,错误消息为json 以将模型级别的Validationerror转换为序列化程序。Validationerror我在序列化程序中使用以下代码 def perform_create(self, validated_data): try: retu
服务器错误500
,而序列化程序中的序列化程序.Validationerror
会生成漂亮且干净的400错误,错误消息为json
以将模型级别的Validationerror
转换为序列化程序。Validationerror
我在序列化程序中使用以下代码
def perform_create(self, validated_data):
try:
return super().perform_create(validated_data)
except exceptions.ValidationError as err:
raise serializers.ValidationError(
f'Model level validation assertion -- {str(err)}'
) from err
它可以工作,但我不能也不想覆盖每一个序列化程序来将Validationerror
转换为序列化程序。验证错误
问题是-是否有任何方法可以捕获所有Validationerror并将其转换为序列化程序。验证错误
from rest_framework.views import exception_handler
from rest_framework.response import Response as DRF_response
from rest_framework import status
from django.core import exceptions
from django.views import View
from django.http import response
def custom_exception_handler(exc: Exception, context: View) -> [response, None]:
response = exception_handler(exc, context)
if isinstance(exc, exceptions.ValidationError):
data = exc.message_dict
return DRF_response(data=data, status=status.HTTP_400_BAD_REQUEST, )
return response
我制作了一个定制的错误处理程序,它捕获所有Django标准验证错误并返回DRF风格的响应