Django REST Framework: Raise Error When Extra Fields Are Present On POST
When you're writing a serializer, it is trivial to specify which fields will be included (via Meta's fields), setting read/write permissions on them and validating them. However, I
Solution 1:
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
Solution 2:
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)
Post a Comment for "Django REST Framework: Raise Error When Extra Fields Are Present On POST"