【发布时间】:2016-07-11 08:18:30
【问题描述】:
所以我有一个QuestionResource:
class QuestionResourse(ModelResource):
def dehydrate(self, bundle):
bundle.data['responses'] = Responses.objects.filter(question_id=bundle.data['id'])
return bundle
class Meta:
resource_name='question'
queryset = Questions.objects.all()
allowed_methods = ['get', 'post']
如果 url 类似于 https://domain.com/api/v1/question/,它应该返回带有属性响应的问题。虽然它们没有被序列化。
{
"date": "2015-10-03T16:53:22",
"id": "1",
"question": "Where is my mind?",
"resource_uri": "/api/v1/question/1/",
"responses": "[<Responses: Responses object>, <Responses: Responses object>, <Responses: Responses object>, <Responses: Responses object>, <Responses: Responses object>]",
"totalresponses": 5
}
如何序列化<Responses: Responses object>?
另外,如何将"responses" 制作成json 数组而不是字符串?
编辑: 在 raphv 的帮助下,我在资源中使用了这段代码:
class ResponseResourse(ModelResource):
class Meta:
resource_name='response'
queryset = Responses.objects.all()
allowed_methods = ['get', 'post']
class QuestionResourse(ModelResource):
responses = fields.ToManyField(ResponseResourse, attribute=lambda bundle: Responses.objects.filter(question_id = bundle.obj.id), full=True)
class Meta:
resource_name='question'
queryset = Questions.objects.all()
allowed_methods = ['get', 'post']
生产:
{
"date": "2015-10-03T16:53:22",
"id": "1",
"question": "Where is my mind?",
"resource_uri": "/api/v1/question/1/",
"responses": [
{
"id": "54",
"resource_uri": "/api/v1/response/54/",
"response": "ooooooo oooooo",
},
{
"id": "60",
"resource_uri": "/api/v1/response/60/",
"response": "uhh, test",
"votes": 0
}]
}
【问题讨论】:
-
Python 中编码的 JSON 始终是字符串。要将其转换为 array,您必须对其进行解码。
json.loads这样做。
标签: python django api serialization tastypie