我有一个稍微复杂的APIView,这使得我无法使用通用ListAPIView来返回查询集。但即使我设置many=True
,我也无法使用ModelSerializer简单地序列化一个简单的Django查询集。
不知怎的,这不起作用:
serializers.py:
class SomeModelSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ['some_field']
views.py:
from rest_framework.response import Response
class SomeAPIView(APIView):
serializer_class = SomeInputSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
# first some business logic, then return results
results = SomeModel.objects.all()
output_serializer = SomeModelSerializer(results, many=True)
return Response(output_serializer.data)
我所得到的只是:'ListSerializer' object is not iterable
。
我做错了什么?
错误:
/projectfolder/venv/lib/python2.7/site-packages/django/template/defaulttags.py in render
try:
values = self.sequence.resolve(context, True)
except VariableDoesNotExist:
values = []
if values is None:
values = []
if not hasattr(values, '__len__'):
values = list(values) ...
len_values = len(values)
if len_values < 1:
return self.nodelist_empty.render(context)
nodelist = []
if self.is_reversed:
values = reversed(values)
values = list(values)
似乎应对错误负责
答案 0 :(得分:2)
以下是使用as_view()网址的作品:
class ListCreateMemberViewSet(generics.ListCreateAPIView):
"""
API endpoint that allows multiple members to be created.
"""
queryset = Member.objects.none()
serializer_class = MemberSerializer
def get_queryset(self):
queryset = Member.objects.all()
return queryset
def create(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)
答案 1 :(得分:1)
遇到了和你一样的问题。我找到了一个快速而简单的错误修复:将序列化数据复制到一个新数组并返回。
results = SomeModel.objects.all()
output_serializer = SomeModelSerializer(results, many=True)
data = output_serializer.data[:]
return Response(data)
这对我有用,希望对你也有用。
答案 2 :(得分:0)
该错误是尝试直接在序列化程序上运行list
的结果。
例如,这将引发以上异常:
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
这不会(区别是我们列出的是output_serializer.data
而不是output_serializer
):
results = Member.objects.all()
output_serializer = MemberSerializer(results, many=True)
all_results = list(output_serializer.data)
all_results += output_serializer.data
我觉得在原始问题中,示例代码与实际代码并非100%匹配。