有什么方法可以更改来自服务器的响应,仅针对 CREATE 和 UPDATE 请求,所以看起来像
{ "root":
[ { "field1": "value1", "field2": "value2", "field3": "value3", "id": 12 ],
"success": true }
代替:
{ "field1": "value1", "field2": "value2", "field3": "value3", "id": 12 }
当然可以。看看钩子:
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
我编写了一个自定义序列化程序以使其工作:
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)
我对这样的代码做了同样的事情
class MyModel:
class Meta:
...
def alter_detail_data_to_serialize(self, request, to_be_serialized):
return {"myRoot": to_be_serialized}