How to return custom JSON in Django REST Framework

0 votes

I am trying to return custom json with get_queryset but always get 404 error in response.

class TestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    def get_queryset(self):
        if self.request.method == "GET":
            content = {'user_count': '2'}
            return HttpResponse(json.dumps(content), content_type='application/json')

If I delete everything starting from def I'll got correct response with standard json data. What I am doing wrong?

Jun 25, 2020 in Python by kartik
• 37,520 points
11,143 views

1 answer to this question.

0 votes

Hello @kartik,

There are 2 ways to custom the response in Class-based views with ModelViewSet

Solution 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'})

Solution 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

Thank You!

answered Jun 25, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to add annotate data in django-rest-framework queryset responses?

Hello @kartik, The queryset returned from get_queryset provides ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
6,112 views
0 votes
1 answer

How to secure APIs for Registration and Login in Django Rest Framework?

Hello @kartik, you cannot have an authentication system ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
2,850 views
0 votes
1 answer

How to disable a method in a ViewSet, django-rest-framework

Hello @kartik, You could keep using viewsets.ModelViewSet and define http_method_names on your ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,880 points
10,815 views
0 votes
1 answer

How to update user password in Django Rest Framework?

Hello @kartik, Using a modelserializer might be an ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,880 points
9,202 views
0 votes
1 answer

How to order_by a JSON from serializers.py file in django rest framework?

Hello @kartik, There's an easy way, just override ...READ MORE

answered Jul 2, 2020 in Python by Niroj
• 82,880 points
5,845 views
0 votes
1 answer

How to return the current user with Django Rest Framework?

Hello @kartik, The best way is to use ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
11,994 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP