Return 从 DRF Serializer 序列化 JSON
Return serialized JSON from DRF Serializer
我有一个自定义序列化程序,它返回 JSON 的字符串表示形式。这个序列化器使用 django.contrib.gis.serializers.geojson.Serializer
比 DRF 序列化器快得多。这个序列化器的缺点是它 returns 一切都已经序列化为一个字符串,而不是作为一个 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()
我认为你可以定义一个自定义渲染器并只传递数据,就像这样,
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]
我有一个自定义序列化程序,它返回 JSON 的字符串表示形式。这个序列化器使用 django.contrib.gis.serializers.geojson.Serializer
比 DRF 序列化器快得多。这个序列化器的缺点是它 returns 一切都已经序列化为一个字符串,而不是作为一个 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()
我认为你可以定义一个自定义渲染器并只传递数据,就像这样,
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]