【发布时间】:2020-06-19 17:08:44
【问题描述】:
我有一个自定义序列化程序,它返回 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()
【问题讨论】:
标签: json django django-rest-framework geojson