【问题标题】:must we render serialized data to json before sending response? DRF我们必须在发送响应之前将序列化数据渲染为 json 吗? DRF
【发布时间】:2018-02-27 09:02:24
【问题描述】:

这个问题的答案让我很困惑。 Multiple Models in Django Rest Framework?

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

答案的作者是这样的:

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

文档中的示例 序列化器 = 评论序列化器(评论) 序列化器.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,
        })

【问题讨论】:

  • 这个# b'{"email是json数据,它转储的json就是这样

标签: json django serialization django-rest-framework response


【解决方案1】:

你不需要这样做。 来自doc

与常规的 HttpResponse 对象不同,您不需要实例化 Response 具有渲染内容的对象。相反,您传入未渲染的数据, 可以由任何 Python 原语组成。

JSONRenderer 也是默认渲染器类,将用于渲染。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 2013-05-30
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多