I've noticed that the Serializer isn't really strict when it comes to rejecting input with unknown fields:
In [1]: from rest_framework import serializers
In [2]: class TestSerializer(serializers.Serializer):
...: foo = serializers.CharField()
...:
In [3]: s = TestSerializer(data=dict(foo='foo', bar='bar'))
In [4]: s.is_valid()
Out[4]: True
Is there a way to configure the Serializer
to return a validation error about bar
being unexpected in this situation?
This definitely works:
Nested and list serializers
This will not work if you use a such a serializer as a field in another serializer. In which case, the child serializer won't have access to initial data and you will get an exception.
Same with a
ListSerializer
(ormany=True
) as the list serializer's child serializer won't get the individualinitial_data
items (there is a github ticket for this).In that case the slightly less clean solution which works all both cases is:
s.data
does not containbar
so what is the use case where it matters?After looking at the docs I didn't see a native solution. You could override
.validate()
to do a check and raiseValidationErrors
that way. I didn't test this with whenpartial=True
so you will want to check that if you're using it.With django REST framework v. 3.3.0 it will be: