Django Rest Framework: Register multiple serializers in ViewSet

2024/10/10 12:20:15

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
Answer

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)
https://en.xdnf.cn/q/69899.html

Related Q&A

Which is most accurate way to distinguish one of 8 colors?

Imagine we how some basic colors:RED = Color ((196, 2, 51), "RED") ORANGE = Color ((255, 165, 0), "ORANGE") YELLOW = Color ((255, 205, 0), "YELLOW") GREEN = Color ((0, 128…

Lambda function behavior with and without keyword arguments

I am using lambda functions for GUI programming with tkinter. Recently I got stuck when implementing buttons that open files: self.file="" button = Button(conf_f, text="Tools opt.",…

How to get type annotation within python function scope?

For example: def test():a: intb: strprint(__annotations__) test()This function call raises a NameError: name __annotations__ is not defined error. What I want is to get the type annotation within the f…

General explanation of how epoll works?

Im doing a technical write-up on switching from a database-polling (via synchronous stored procedure call) to a message queue (via pub/sub). Id like to be able to explain how polling a database is vas…

How to return cost, grad as tuple for scipys fmin_cg function

How can I make scipys fmin_cg use one function that returns cost and gradient as a tuple? The problem with having f for cost and fprime for gradient, is that I might have to perform an operation twice…

n-gram name analysis in non-english languages (CJK, etc)

Im working on deduping a database of people. For a first pass, Im following a basic 2-step process to avoid an O(n^2) operation over the whole database, as described in the literature. First, I "b…

How to retrieve all the attributes of LDAP database

I am using ldap module of python to connect to ldap server. I am able to query the database but I dont know how to retrieve the fields present in the database, so that I can notify the user in advance …

Why would this dataset implementation run out of memory?

I follow this instruction and write the following code to create a Dataset for images(COCO2014 training set)from pathlib import Path import tensorflow as tfdef image_dataset(filepath, image_size, batch…

Paramiko: Creating a PKey from a public key string

Im trying to use the SSH protocol at a low level (i.e. I dont want to start a shell or anything, I just want to pass data). Thus, I am using Paramikos Transport class directly.Ive got the server side d…

Appending to the end of a file in a concurrent environment

What steps need to be taken to ensure that "full" lines are always correctly appended to the end of a file if multiple of the following (example) program are running concurrently.#!/usr/bin/e…