[Django]-Django REST Framework: raise error when extra fields are present on POST

29👍

Came across this question and found that using object level validation is a bit easier. This entails simply defining a validate method:

class ModelASerializer(serializers.ModelSerializer):
    ...
    def validate(self, data):
        if hasattr(self, 'initial_data'):
            unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys())
            if unknown_keys:
                raise ValidationError("Got unknown fields: {}".format(unknown_keys))
        return data
👤amilli

4👍

You can do that by overriding the is_valid() method of the serializer. Here, we will check if any of the key in the payload is not a serializer field using filter() and lambda functions.

If filter() returns some fields which are not in the serializer fields, then we raise a ValidationError. Else, we call the super() method and it will then perform the normal serializer validation.

from django.core.exceptions import ValidationError

class MySerializer(..):

    def is_valid(self, raise_exception=False):
        if hasattr(self, 'initial_data'):
            payload_keys = self.initial_data.keys() # all the payload keys
            serializer_fields = self.fields.keys() # all the serializer fields
            extra_fields = filter(lambda key: key not in serializer_fields , payload_keys) 
            if extra_fields:
                raise ValidationError('Extra fields %s in payload'%extra_fields)
        return super(MySerializer, self).is_valid(raise_exception)

Leave a comment