Reputation: 71
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
}
]
Upvotes: 0
Views: 3908
Reputation: 88499
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})
Upvotes: 1