'listserializer' When Serializing A Queryset Using Django Rest Framework
I have a slightly complicated APIView which makes that I can't use a generic ListAPIView to return a queryset. But I can't seem to simply serialize a simple Django queryset using a
Solution 1:
Was running into the same problem as you did. I found a quick and simple fix for the error: Copy the serializer data to a new array and return that.
results = SomeModel.objects.all()
output_serializer = SomeModelSerializer(results, many=True)
data = output_serializer.data[:]
return Response(data)
This works for me, hopefully for you as well.
Solution 2:
Below works for me using an as_view() url:
classListCreateMemberViewSet(generics.ListCreateAPIView):
"""
API endpoint that allows multiple members to be created.
"""
queryset = Member.objects.none()
serializer_class = MemberSerializer
defget_queryset(self):
queryset = Member.objects.all()
return queryset
defcreate(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
results = Member.objects.all()
output_serializer = MemberSerializer(results, many=True)
data = output_serializer.data[:]
return Response(data)
Solution 3:
The error is a result of trying to run a list
on a serializer directly.
For example, this would raise the above exception:
results = Member.objects.all()
output_serializer = MemberSerializer(results, many=True)
all_results = list(output_serializer) # this line here
all_results += output_serializer # or this line here
And this would not (difference is that we are listing output_serializer.data
instead of output_serializer
):
results = Member.objects.all()
output_serializer = MemberSerializer(results, many=True)
all_results = list(output_serializer.data)
all_results += output_serializer.data
I have the feeling that in the original question, the example code was not 100% matching the actual code.
Post a Comment for "'listserializer' When Serializing A Queryset Using Django Rest Framework"