close

How to return custom JSON in Django REST Framework

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to return custom JSON in Django REST Framework in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to return custom JSON in Django REST Framework?

  1. How to return custom JSON in Django REST Framework?

    custom in views.py
    class StoryViewSet(viewsets.ModelViewSet): permission_classes = (permissions.AllowAny,) queryset = Story.objects.all() serializer_class = StorySerializer

  2. return custom JSON in Django REST Framework

    custom in views.py
    class StoryViewSet(viewsets.ModelViewSet): permission_classes = (permissions.AllowAny,) queryset = Story.objects.all() serializer_class = StorySerializer

Method 1

custom in views.py

class StoryViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.AllowAny,)
    queryset = Story.objects.all()
    serializer_class = StorySerializer

    def retrieve(self, request, *args, **kwargs):
        # ret = super(StoryViewSet, self).retrieve(request)
        return Response({'key': 'single value'})

    def list(self, request, *args, **kwargs):
        # ret = super(StoryViewSet, self).list(request)
        return Response({'key': 'list value'})

Method 2

custom in serializers.py (I recommend this solution)

class StorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Story
        fields = "__all__"

    def to_representation(self, instance):
        ret = super(StorySerializer, self).to_representation(instance)
        # check the request is list view or detail view
        is_list_view = isinstance(self.instance, list)
        extra_ret = {'key': 'list value'} if is_list_view else {'key': 'single value'}
        ret.update(extra_ret)
        return ret

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read