1

I have a APIView that provides my model instances. I want to use different serializers based on url parameters, beacause I want to serve different fields based on parameter. I didn't want to use if else check for all situations, so I used a function that provide serializer from serializer objects dict based on type key. Is there a good solution? Does anyone have a better suggestion? Also what are you thinking about use different endpoints instead of this method. Here is the code:

urls.py

from django.urls import path
from .views import MySerializerTestView

urlpatterns = [
    path('<slug:type>', MySerializerTestView.as_view()),
]

models.py

from django.db import models
class MyModel(models.Model):
    field_first = models.CharField(max_length=10)
    field_second = models.CharField(max_length=10)
    field_third = models.CharField(max_length=10)

views.py

from .models import MyModel
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import MyFirstSerializer,MySecondSerializer,MyThirdSerializer

class MySerializerTestView(APIView):
    def get(self, request, **kwargs):
        my_data = MyModel.objects.all()
        serializer = self.get_serializer(self.kwargs['type'],my_data)
        return Response(serializer.data)


    def get_serializer(self,type,data):
        my_serializers = {
        'first':MyFirstSerializer(data,many=True),
        'second':MySecondSerializer(data,many=True),
        'third':MyThirdSerializer(data,many=True),
        }
        return my_serializers[type]

serializers.py

from .models import MyModel
from rest_framework import serializers

class MyFirstSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['field_first']

class MySecondSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['field_second']


class MyThirdSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['field_third']

1 Answer 1

6

You can send a parameter or select the serializer based on the action that is taken.

In your "view.py" file you can use the "get_serializer_class (self)" method to do it.

def get_serializer_class(self):
    if  'parameter' in self.request.query_params:
        return ParameterSerializer

    if self.action == "list" or self.action == 'retrieve':
        return ListSerializer
    else:
        return CreateSerializer
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your advice. But it is not the answer I'm looking for. I don't want to use if else checks. Because there are a lot of possibilities and I have to write if else check for each condition with this method. I'm looking for is there better solution.
You can adapt it to your needs, you should not necessarily use "If" is just an example.using "self.request.query_params.get ('param', '')" you get the value, which can be an index for example : "type = self.request.query_params.get ('param', '') return my_serializers [type]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.