get_serializer_class don't work in GenericViewSet

358 views
Skip to first unread message

Cristian Benavides Jimenez

unread,
Nov 21, 2019, 8:21:44 PM11/21/19
to Django REST framework
Hi everybody,

I try use a two serializers in one view inherits from GenericViewSet with the method get_serializer_class

Here a little piece of my code:

class RandomViewSet(ListModelMixin, GenericViewSet):
    permission_classes = (IsAuthenticated, )
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, ]
    search_fields = ['some_field', 'some_field', 'some_field', ]
    ordering_fields = ['pk', ]
    ordering = ['pk', ]
    lookup_field = 'pk'
    serializer_class = OneSerializer
    serializers = {
        'list': OneSerializer,
        'create': TwoSerializer,
    }

    def get_serializer_class(self, *args, **kwargs):
        print('THIS METHOD DON\'T WORK')
        return self.serializers.get(self.action)

    def create(self, request, *args, **kwargs):
        print('Data is not validated :(')



Any help for this?

Greetings,


Rob Deutsch

unread,
Nov 21, 2019, 9:57:55 PM11/21/19
to Django REST framework
I am not a DRF expert but it looks like that should work. Would you mind providing a bit more information?

Is get_serializer_class() called? Or is it never even called?

Linovia

unread,
Nov 22, 2019, 4:02:33 AM11/22/19
to Django REST framework
Hi,

Can you elaborate on the « don’t work » part ?
I have been using get_serializer_class and it has always worked well to me with GenericViewSet.

Regards,
Xavier O.
Linovia
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/438adf7c-e2d5-480c-8716-9bd83116c902%40googlegroups.com.

Jason

unread,
Nov 22, 2019, 6:42:57 PM11/22/19
to Django REST framework
http://www.cdrf.co/3.9/rest_framework.viewsets/GenericViewSet.html#get_serializer_class

Note there’s no args or kwargs in the default implementation, but you have them in yours

Carl Nobile

unread,
Nov 30, 2019, 1:41:02 PM11/30/19
to Django REST framework
It seems that you have both the

serializer_class

member object and the 

get_serializer_class

method set. Remove the 

serializer_class.
Reply all
Reply to author
Forward
0 new messages