Non-required serializer related fields · Issue #3976 · encode/django-rest-framework (original) (raw)

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.