pythondjangodjango-rest-frameworkopenapidrf-spectacular

drf_spectacular.utils.PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context'


I am using a PolymorphicProxySerializer provided by drf_spectacular but I am getting a strange error when attempting to load the schema

usage

    @extend_schema(
        parameters=[NoteQueryParameters],
        responses=PolymorphicProxySerializer(
            component_name="NoteSerializer",
            serializers=[NoteSerializer, NoteSerializerWithJiraData],
            resource_type_field_name=None,
        ),
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

serializers


class CleanedJiraDataSerializer(serializers.Serializer):
    key = serializers.CharField(max_length=20, allow_null=True)

class BugSerializer(serializers.Serializer):
    failures = serializers.CharField(max_length=10, required=False, allow_null=True)
    suite = serializers.CharField(max_length=100, required=False, allow_null=True)
    notes = serializers.CharField(max_length=1000, required=False, allow_null=True)
    tags = StringListField(required=False, allow_null=True, allow_empty=True)
    testCaseNames = StringListField(required=False, allow_null=True, allow_empty=True)
    testCaseIds = StringListField(required=False, allow_null=True, allow_empty=True)
    jira = CleanedJiraDataSerializer(required=False, allow_null=True)


class BugSerializerWithJiraData(BugSerializer):
    jira = serializers.DictField()

class NoteSerializer(serializers.ModelSerializer):
    bug = serializers.ListField(child=BugSerializer())

    class Meta:
        model = Notes
        fields = "__all__"


class NoteSerializerWithJiraData(serializers.ModelSerializer):
    bug = serializers.ListField(child=BugSerializerWithJiraData())

    class Meta:
        model = Notes
        fields = "__all__"

Basically, if a boolean query parameter is added to the request, I will inject some dynamic data fetched from the jira api. I am trying to update the api docs to represent to two distinct possible schema

PolymorphicProxySerializer.__init__() got an unexpected keyword argument 'context'

Solution

  • You need to pass many=True when you instantiate PolymorphicProxySerializer, since you're decorating a ListView.

    @extend_schema(
        parameters=[NoteQueryParameters],
        responses=PolymorphicProxySerializer(
            component_name="NoteSerializer",
            serializers=[NoteSerializer, NoteSerializerWithJiraData],
            resource_type_field_name=None,
            many=True
        ),
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)