0

有什么方法可以更改来自服务器的响应,仅针对 CREATE 和 UPDATE 请求,所以看起来像

{ "root": 
    [ { "field1": "value1", "field2": "value2", "field3": "value3", "id": 12 ],
"success": true }

代替:

{ "field1": "value1", "field2": "value2", "field3": "value3", "id": 12 } 
4

3 回答 3

1

当然可以。看看钩子:

alter_list_data_to_serialize(self, request, data)

http://django-tastypie.readthedocs.org/en/latest/resources.html#alter-list-data-to-serialize

alter_detail_data_to_serialize(self, request, data)

http://django-tastypie.readthedocs.org/en/latest/resources.html#alter-detail-data-to-serialize

于 2013-07-12T06:24:42.010 回答
0

我编写了一个自定义序列化程序以使其工作:

class CustomJSONSerializer(Serializer):
    def to_json(self, data, options=None):
        options = options or {}
        data = self.to_simple(data, options)
        root = {}
        root['success'] = True
        if data.has_key('meta'):
            meta = data['meta']
            del data['meta']
            root.update(meta)
        objects = []
        if data.has_key('objects'):
            objects = data['objects']
            del data['objects']
        if not objects:
            objects = [data]
        root['root'] = objects
        return simplejson.dumps(root, cls=json.DjangoJSONEncoder, sort_keys=True) 
于 2013-07-11T13:56:06.867 回答
0

我对这样的代码做了同样的事情

class MyModel: class Meta: ... def alter_detail_data_to_serialize(self, request, to_be_serialized): return {"myRoot": to_be_serialized}

于 2014-06-05T11:13:48.233 回答