问题描述
我正在尝试在Django GET请求中调用序列化程序,但它显示了一个TypeError:"ListSerializer"类型的对象不可JSON序列化如果我在某个地方出错了,请帮助我.预先感谢.
Iam trying to call a serializer in django GET request But it shows up an TypeError: Object of type 'ListSerializer' is not JSON serializablePlease help me if i went wrong somewhere. Thanks in Advance.
class Member(MemberMixin, APIView):
serializer_class = MemberSerializers
def get(self, request, format=None):
objects = MemberSerializers(Members.objects.all(), many=True)
self.meta_data = "GET"
self.module = "Member"
self.data = objects
if objects is None:
self.error = "datas are not found"
return Response(self.response_obj, status=status.HTTP_404_NOT_FOUND)
else:
return Response(self.response_obj, status=status.HTTP_200_OK)
pass
序列化器代码如下:
from .models import Members
class MemberSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = Members
fields = ('username', 'fullname', 'phone','address','memberid')
# exclude = ['']
pass
MemberMixins代码如下:
MemberMixins code as follows:
class MemberMixin(object):
meta_data = dict()
data = dict()
error = dict()
def __init__(self):
self.meta_data = dict()
self.data = dict()
self.error = dict()
self.json_schema = None
super().__init__()
@property
def response_obj(self):
resp = dict()
resp['meta'] = self.meta_data
if self.error:
resp['error'] = self.error
else:
resp['data'] = {
'detail': self.data,
}
return resp
pass
推荐答案
问题是您正在将序列化器本身而不是序列化的数据发送给响应.您应该将其更改为:
The problem is that you're sending the serializer itself, rather than the serialized data, to the response. You should change it to:
self.data = objects.data
但是,话说回来,大部分代码是完全不必要的,您已经绕过了Django和DRF已经为您完成的大部分工作.删除您的mixin并使用ListAPIView.
But that said, most of this code is totally unnecessary, You're bypassing most of .he things that Django and DRF do for you already. Remove your mixin and use a ListAPIView.
这篇关于序列化程序调用显示TypeError:类型为'ListSerializer'的对象不是JSON可序列化的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!