我们必须在发送响应之前将序列化数据渲染到 json 吗? DRF

must we render serialized data to json before sending response? DRF

这个问题的答案让我很困惑。

答案是在响应中发送多个模型的问题。我有相同的用例。

回答作者是这样的:

def get(self, request, format=None, **kwargs):
    cart = get_cart(request)
    cart_serializer = CartSerializer(cart)
    another_serializer = AnotherSerializer(another_object)

    return Response({
        'cart': cart_serializer.data,
        'another': another_serializer.data,
        'yet_another_field': 'yet another value',
    })

但我会遵守文档。

http://www.django-rest-framework.org/api-guide/serializers/#serializing-objects

文档中的示例 serializer = CommentSerializer(注释) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}

from rest_framework.renderers import JSONRenderer

json = JSONRenderer().render(serializer.data)
json
# b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'

所以是哪一个?我JSON还是不JSON。这就是我目前拥有的。

def get(self, request, format=None):
        searchcityqueryset = SearchCity.objects.all()
        neighborhoodqueryset = SearchNeighborhood.objects.all()
        serializedsearchcity = SearchCitySerializer(searchcityqueryset)
        serializedsearchneighborhood = SearchNeighborhoodSerializer(neighborhoodqueryset)
 jsonsearchcity = JSONRenderer().render(serializedsearchcity.data)
        jsonsearchneighborhood = JSONRenderer().render(serializedsearchneighborhood.data)
 return Response({
            'searchcity': jsonsearchcity,
            'searchneighborhood': jsonsearchneighborhood,
        })

你不需要这样做。 来自 doc:

Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.

另外 JSONRenderer 是默认渲染器 class,将用于渲染。

所以你可以简单地这样做:

return Response({
    'cart': cart_serializer.data,
    'another': another_serializer.data,
    'yet_another_field': 'yet another value',
})