Skip to content

Not being able to represent array serializer in get_serializer_class #8093

@hnykda

Description

@hnykda

(moved here #8109)

Hey.

I want an endpoint that returns simple array of items of type Log. I am aware that when initializing that, I should use many=True. But to also nicely generate the docs, I want to somehow represent that in get_serializer_class:

class ProcessingJobViewSet(GenericViewSet):
    queryset = ProcessingJob.objects.all()
    serializer_class = ProcessingJobSerializer

    def get_serializer_class(self):
        if self.action == "logs":
            return LogSerializer
        return self.serializer_class

    @action(detail=True, url_path="logs")
    def logs(self, request: Request, pk: int) -> Response:
        job = self.get_object()
        logs = retrieve_logs(job)
        return Response(LogSerializer(logs, many=True).data)

But how should I do it given that it needs to return the class def, not its instance? If I try to return ListSerializer(child=LogSerializer) it complains about child not being initialized and when I do initialize it, then it complains about ListSerializer object not callable.

The only workaround I found is to do:

class LogsSerializer(serializers.Serializer):
  results = LogSerializer(many=True)

but then I have a useless results key in the response.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions