1

I have two models: ModelA and ModelB, with their corresponding serializers ModelASerializer and ModelBSerializer

In a specific viewset, called MyViewSet i have the follwing structure:

class MyViewSetRoot(viewsets.ModelViewSet):
    http_method_names = ["get"]
    # The returned values are of type "ModelA", so I need it to use that serializer
    serializer_class = ModelASerializer
    queryset = ""

Finally, in my actual view, I do something like this:

class MyViewSet(MyViewSetRoot):
    get(self, request: HttpRequest, *args, **kwargs) -> Response:
        ModelA_queryset = ModelA.objects.all()
        return Response(
            data=ModelA_queryset,
            status=status.HTTP_200_OK,
        )

I would expect in that case for the queryset to be serialized using the ModelASerializer that I specified in the serializer_class field. However, I get the error

Object of type ModelA is not JSON serializable

If I do this instead:

class MyViewSet(MyViewSetRoot):
    get(self, request: HttpRequest, *args, **kwargs) -> Response:
        ModelA_queryset = ModelA.objects.all()
        serialized_queryset = ModelASerializer(ModelA_queryset, many=True)
        return Response(
            data=serialized_queryset.data,
            status=status.HTTP_200_OK,
        )

It works just fine, but I want to avoid serializing explicitly in the view.

Any ideas on what could be actually going on? Am I forced to serialize explicitly in this case?

1 Answers1

0

I think you don't need to customize the get function. In ModelViewSet, the function for the GET API, is list or retrieve. But you don't need to redefine it.

class MyViewSetRoot(viewsets.ModelViewSet):
    http_method_names = ["get"]
    serializer_class = ModelASerializer
    queryset = ModelA.objects.all()

class MyViewSet(MyViewSetRoot):
    pass
Metalgear
  • 3,391
  • 1
  • 7
  • 16