Stuart Buckingham
Stuart Buckingham

Reputation: 1784

Return serialized JSON from DRF Serializer

I have a custom serializer that is returning a string representation of JSON. This serializer uses django.contrib.gis.serializers.geojson.Serializer which is much faster than the DRF serializer. The downside of this serializer is that it returns everything already serialized into a string, rather than as a JSON serializiable object.

Is there a way to shortcut the DRF obj>json string process and just pass the string as the json response?

Currently I am doing the following, but the obj>string>dict>string process is not ideal:

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))

Which is implemented (simplified version) in the view:

from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet

class GeoJSONPlaceViewSet(ListModelMixin, GenericViewSet):
    serializer_class = GeoJSONFastSerializer
    queryset = Places.objects.all()

Upvotes: 1

Views: 1398

Answers (1)

cabesuon
cabesuon

Reputation: 5270

I think that you could define a custom renderer and just pass the data, something like this,

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

and in the view just add

renderer_classes = [AlreadyJSONRenderer]

Upvotes: 3

Related Questions