我有一个自定义序列化程序,该序列化程序返回JSON的字符串表示形式。该串行器使用django.contrib.gis.serializers.geojson.Serializer
,它比DRF串行器快得多。该序列化程序的缺点是,它会将已序列化的所有内容返回为字符串,而不是作为JSON可序列化的对象。
有没有一种方法可以简化DRF obj> json字符串过程,并将字符串作为json响应传递?
当前我正在执行以下操作,但是obj> string> dict> string过程并不理想:
from django.contrib.gis.serializers.geojson import Serializer
from json import loads
class GeoJSONFastSerializer(Serializer):
def __init__(self, *args, **kwargs):
self.instances = args[0]
super().__init__()
@property
def data(self):
# The use of json.loads here to deserialize the string,
# only for it to be reserialized by DRF is inefficient.
return loads(self.serialize(self.instances))
在视图中实现了哪些版本(简化版)
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
class GeoJSONPlaceViewSet(ListModelMixin, GenericViewSet):
serializer_class = GeoJSONFastSerializer
queryset = Places.objects.all()
答案 0 :(得分:1)
我认为您可以定义一个自定义渲染器并只传递数据,像这样
from django.utils.encoding import smart_unicode
from rest_framework import renderers
class AlreadyJSONRenderer(renderers.BaseRenderer):
media_type = 'application/json'
format = 'json'
def render(self, data, media_type=None, renderer_context=None):
return data
,然后在视图中添加
renderer_classes = [AlreadyJSONRenderer]