如何通过DRF返回自定义状态代码?

时间:2018-05-22 21:36:41

标签: django django-rest-framework

如果用户发送POST请求以创建作业,但该作业已存在 - 我正在尝试返回202.

相反,它返回400 ..

视图

def post(self, request, format=None):
    serializer = CreateJobSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

串行

class CreateJobSerializer(GenericSerializer):
    class Meta:
        model = Job
        fields = ('name')

    def create(self, validated_data):
        try:
            obj = Job.objects.create(**validated_data)
            return obj
        except:
            return Response(serializer.errors, status=status.HTTP_202_ACCEPTED)

我假设如果在该模型上违反了unique = true,Job.objects.create将失败,如果是这种情况我会期望返回202。我做错了什么?

是否因为在验证期间实际捕获了unique = true错误,所以实际上从未调用create()?

1 个答案:

答案 0 :(得分:0)

我认为你可以capture the Validation Error然后根据自己想要的状态制作自定义回复(在这种情况下为202)。

我还没试过,但这可能有用:

try:
    if (serializer.is_valid(raise_exception=True)):
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
except ValidationError as msg:
    if str(msg) == "This Email is already taken":
        return Response(
            {'ValidationError': str(msg)},
            status=status.HTTP_202_ACCEPTED
        )
    else:
        return Response(
            {'ValidationError': str(msg)},
        status=status.HTTP_400_BAD_REQUEST
        )