0

How to return a list of objects in Django Rest Framework.I am calling a function which returns list of objects.

from rest_framework.views import APIView
from rest_framework.response import Response
import json

class MyView(APIView):
    from .serializers import MySerializer
    from app.permissions import MyPermissionClass
    from .models import MyModel

    serializer_class = MySerializer
    queryset = MyModel.objects.all()
    permission_classes = (MyPermissionClass,)
    pagination_class = None

    def get(self, request, *args, **kwargs):
        data=myfunction(a,b,c)
        # data={list}<class 'list'>: [<User: Negiiii | negiiii>, <User: Negiiii | negiiii>]
        data=json.dumps(data)
        return Response({"data":data})

Result that I need:

[
  {
    "name":"Negi",
    "rollno":14
   },
  {
    "name":"Negi",
    "rollno":13
  }
]
2
  • Is that a User model Queryset? Commented May 20, 2019 at 5:02
  • can you add the MySerializer class? Commented May 20, 2019 at 5:12

1 Answer 1

1

You can use DRF Serializers to serialize the data. First you need to define a serializer class as,

# serializers.py
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('name', 'rollno')

and then, use the UserSerializer in your views as,

def get(self, request, *args, **kwargs):
    data = myfunction(a, b, c)
    response_data = UserSerializer(data, many=True)
    return Response({"data": response_data.data})
Sign up to request clarification or add additional context in comments.

2 Comments

Instead of using response_data = MySerializer(data, many=True) I have used response=self.get_serializer(data, many=True) Thank you for your help!
I could've written a better answer if you'd provide right info at the right time :)

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.