Home > Mobile >  serializer_action_class not working in modelviewset in DRF
serializer_action_class not working in modelviewset in DRF

Time:10-27

I am trying to make serializer class dynamic, but its not working. I have a default serializer class where as a dynamic serializer class for different actions. Here it is my modelviewset.

My view:

class ClassView(viewsets.ModelViewSet):
    queryset = Class.objects.all()
    serializer_class = ClassSerializer
    serializer_action_classes = {
        'put': AddStudentstoClassSerializer,
    }

    def get_serializer_class(self):

        """
            returns a serializer class based on the http method
        """
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            print("iam ClassSerializer")
            return super(ClassView, self).get_serializer_class()

My function inside the same modelviewset above

    @action(detail=True, methods=['put'])
    def add_remove_students(self, request, *args, **kwargs):
      ................

MY url is as below:

urlpatterns = [
    path("class/<int:pk>/<slug:slug>/",views.ClassView.as_view({"put": "add_remove_students"}),
    ),
]

Here in the above code snippet, I try to get AddStudentstoClassSerializer inside the add_remove_students function but it is not working. As we can see the print("iam ClassSerializer") code is working, however what i wanted or AddStudentstoClassSerializer.

CodePudding user response:

First of all your serializer_action_classes dictionary should look like this:

serializer_action_classes = {
    'add_remove_students': AddStudentstoClassSerializer,
}

because self.action return name of the action, not the method name. What you mean to use is self.request.method attribute which shoud return PUT in this case..

But there's better way to achieve your goal:

@action(detail=True, methods=['put'], serializer_class=AddStudentstoClassSerializer)
    def add_remove_students(self, request, *args, **kwargs):

action decorators can ovveride used serializer_class by themselves.

  • Related