【发布时间】: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