Checklist
Steps to reproduce
create a serializer that subclasses serializers.Serializer with a non-required primary key relation
class SearchSerializer(serializers.Serializer):
q = serializers.CharField()
user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False)
call the serializer in with a request that doesn't have a user parameter
serializer = SearchSerializer(data={"q": "hello world"})
serializer.is_valid(raise_exception=True)
print(serializer.data) # <- KeyError 'user' is raised here
Expected behavior
the serializer should validate that the field q exists and ignore validating the user field if it is not supplied in the request data. The an example request
should be valid, and user should either be None or not included in the serializer.data
Actual behavior
the serializer raises a KeyError on serializer.data if user is not included in the request data.
Checklist
masterbranch of Django REST framework.Steps to reproduce
create a serializer that subclasses
serializers.Serializerwith a non-required primary key relationcall the serializer in with a request that doesn't have a user parameter
Expected behavior
the serializer should validate that the field
qexists and ignore validating theuserfield if it is not supplied in the request data. The an example request{ "q": "hello world" }should be valid, and user should either be
Noneor not included in theserializer.dataActual behavior
the serializer raises a
KeyErroronserializer.dataif user is not included in the request data.