Django REST拒绝错误的PATCH数据

时间:2016-04-29 23:16:11

标签: rest django-rest-framework

所以,我有一个补丁请求,看起来像我的/ user / 1端点。显然,“sdfsdf”不是我的User模型的有效属性。当我修补以下内容时,我得到200响应,但它应该抛出400或422,因为“sdfsdf”不是有效字段。我如何拒绝不良补丁?

{
    "sdfsdf": "sdfsdf"
    "username": "alex"
}

我的用户序列化程序看起来像这样:

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ("first_name", "id", "username")

我的用户视图如下所示:

class UserViewSet(viewsets.ViewSet):
serializer_class = UserSerializer

def list(self, request, pk=None):
    queryset = User.objects.filter()
    serializer = UserSerializer(queryset, many=True)
    return Response(serializer.data)

def retrieve(self, request, pk=None):
    queryset = User.objects.filter()
    user = get_object_or_404(queryset, pk=pk)
    serializer = UserSerializer(user)
    return Response(serializer.data)

def partial_update(self, request, pk=None):
    queryset = User.objects.filter()
    user = get_object_or_404(queryset, pk=pk)

    if not request.user.pk == user.pk:
        raise PermissionDenied

    serializer = UserSerializer(user, data=request.data, partial=True)

    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)

1 个答案:

答案 0 :(得分:0)

您可以覆盖UserSerializer.validate方法以提供对象级别验证(请在docs中阅读更多内容)。

例如:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("first_name", "id", "username")

    def validate(self, data):
        invalid_keys = set(self.initial_data.keys()) - set(self.fields.keys())
        if invalid_keys:
            raise serializers.ValidationError('invalid keys passed into serializer: {0}'.format(invalid_keys))
        return data