简体   繁体   中英

Django Rest Framework: Register multiple serializers in ViewSet

I'm trying to create a custom API (not using models), but its not showing the request definition in the schema (in consequence, not showing it in swagger). My current code is:

views.py

class InfoViewSet(viewsets.ViewSet):

    @list_route(methods=['POST'])
    def some_method(self, request):
       data = JSONParser().parse(request)
       serializer = GetInfoSerializer(data=data)
       serializer.is_valid(raise_exception=True)
       info = get_data_from_elsewhere(serializer.data)
       return Response(info)

urls.py

router.register(r'^info', InfoViewSet, base_name='info')

serializers.py

class InfoSomeMethodSerializer(serializers.Serializer):

  list_id = serializers.ListField(child=serializers.IntegerField())
  password = serializers.CharField()

And it appears in swagger, but just the response part. How can I register the post parameters? I'm also not sure if I'm using DRF correctly (I'm new) so any correction will be appreciated.

--

edit: I tried the serializer_class argument suggested by Linovia and didn't work, I got:

TypeError: InfoViewSet() received an invalid keyword 'serializer_class'

I tried overriding get_serializer_class method and didn't work either:

def get_serializer_class(self):
    if self.action == 'some_method':
        return InfoSomeMethodSerializer

For people running this into the future - when you add the serializer_class attribute to the @action decorator of a view which inherits from viewsets.ViewSet , it will indeed by default give you a TyperError, as OP mentioned:

TypeError: InfoViewSet() received an invalid keyword 'serializer_class'

To overcome this, simply add serializer_class = None as a class variable to your view.

Example of editing OPs code:

class InfoViewSet(viewsets.ViewSet):
    # ↓ ADD THIS!
    serializer_class = None 

    # Now you can add serializer_class without geting a TypeError ↓
    @list_route(methods=['POST'], serializer_class=GetInfoSerializer)
    def some_method(self, request):
       data = JSONParser().parse(request)
       serializer = GetInfoSerializer(data=data)
       serializer.is_valid(raise_exception=True)
       info = get_data_from_elsewhere(serializer.data)
       return Response(info)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM