DRF序列化Django模型报错:ListSerializer无法JSON序列化
解决DRF序列化Comment模型返回时的"Object of type ListSerializer is not JSON serializable"错误
问题根源
你在视图中直接将序列化器实例传递给了Response,但DRF的Response需要的是序列化后的数据(即序列化器的.data属性),而不是序列化器对象本身。当设置many=True时,序列化器会返回ListSerializer实例,这个对象无法被JSON序列化,因此触发错误。
修复方法
修改API视图的get方法,返回序列化器的.data属性即可:
class ListCommentsApiView(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.AllowAny] def get(self, request: HttpRequest) -> Response: comments = Comment.objects.all() serialized_comments = CommentModelSerializer(instance=comments, many=True) # 返回序列化后的data属性,而不是序列化器实例 return Response(serialized_comments.data)
补充说明
- DRF序列化器在完成数据序列化后,会将结果存储在
.data属性中,这个属性是标准的Python字典/列表结构,可以直接被Response处理并序列化为JSON。 - 当使用
many=True时,.data会返回一个包含所有序列化后对象的列表,符合API返回的格式要求。
内容的提问来源于stack exchange,提问作者Shervin.bdn
相关产品推荐
相关产品推荐

