Search code examples
djangodjango-views

Django: adding a second 'detailed' view for retrieving extra information


I have set up my urls.py and views.py file to serialize my Projects model in two different ways: detailed information for the 'retrieve' action, and abbreviated information for the 'list' action.

This works well so far:

/projects/ = list of projects with abbreviated information
/projects/12 = detailed information about a specific project (id=12)

urls.py:

router.register(r'projects', ProjectViewSet, basename='project')

views.py

class ProjectViewSet(viewsets.ModelViewSet):

    serializer_class = ProjectSerializerMini

    # Select a serializer according to the action (i.e.: 'retrieve' will
    # return a more detailed serialized data than 'list')
    action_serializers = {
        'retrieve': ProjectSerializerDetail,
        'list': ProjectSerializerList
    }

    def get_serializer_class(self):

        return self.action_serializers.get(self.action, self.serializer_class)


My question is: would it be possible, using the ViewSet framework, to summon a third serializer that would return, say, an even more detailed set of information.

Ex.: /projects/12/extradetail

The reason for this is that some of these records include geospatial data that is quite voluminous. I would only want to retrieve this extra detail in some cases


Solution

  • You can overwrite which serializer is used in each viewset

    class ProjectViewSet(viewsets.ModelViewSet):
        @action(detail=True, methods=['get'], serializer_class=SpecialSerializer)
        def special(self, request, pk=None):
            return super().retrieve(request, args, kwargs)
            
    
        def get_serializer_class(self):
            if self.action == 'list':
                return serializers.SimpleSerializer
            if self.action == 'retrieve':
                return serializers.DetailedSerializer
            return serializers.DefaultSerializer
    

    in conjunction with this you can create custom actions with the @action decorator