Django rest framework, use different serializers in the same ModelViewSet

Django rest framework allows the creation and the use of different serializers (objects allowing complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types) within the same ModelViewSet.

For instance, if you would like to use PutHeroSerializer as a serializer class to perform PUT requests and RetrieveHeroSerializer to perform GET requests: conditioning on the request method to decide which serializer to use seems to be the best choice.

On serializers.py :

from django.contrib.auth.models import User, Group
from .models import Hero
from rest_framework import serializers


class HeroSerializer(serializers.ModelSerializer):   

    class Meta:
        model = Hero
        fields = '__all__'

class RetrieveHeroSerializer(serializers.ModelSerializer):   

    class Meta:
        model = Hero
        fields = '__all__'
        depth = 1 # <- Hero contains a ForeignKey field, depth allows to read its data

On views.py

from django.shortcuts import render
from .models import Hero
from .serializers import ParameterSerializer, RetrieveParameterSerializer
from rest_framework import permissions, generics, viewsets, filters
from django_filters.rest_framework.backends import DjangoFilterBackend


class HeroViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Hero to be viewed or edited.
    """
    queryset = Hero.objects.all().order_by('-name')

    def get_serializer_class(self):
        if self.request.method == 'PUT':
            return HeroSerializer
        else:
            return RetrieveHeroSerializer
   
    filter_backends = [filters.SearchFilter]
    search_fields = ['name', 'parameter_order']

The Hero model contains a ForeignKey field, when we try to update its value via an HTTP client (Angular App for example) we need to use a HeroSerializer (possible only without depth), otherwise, we use the RetrieveHeroSerializer.

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

Open chat
Powered by