Convert a queryset to json using tastypie resource

烈酒焚心 提交于 2019-11-30 03:34:41

问题


I have a tastypie resource for a model. I also have a view which comes up with a queryset which needs to be serialised and sent to client. I am looking for a way to let tastypie resource handle the serialisation and dehydration of the queryset.

I see that I can pass a single object to

[Resource.build_bundle(self, obj=None, data=None, request=None)][1]

to create a bundle and then pass the bundle to

[Resource.full_dehydrate(self, bundle)][2]

and finally call

[Resource.serialize(self, request, data, format, options=None)][3]

on the dehydrated data.

But I want to convert full queryset to json and not just a single object. Maybe all I need is a way to convert full queryset to bundle.

Any help is appreciated!


回答1:


This was bugging me too, but I think I found the answer after looking through tastypie's code on github.

This will make a bunch of bundles.

bundles = [Resource.build_bundle(obj=q, request=request) for q in Queryset]

This will perform the dehydration.

data = [Resource.full_dehydrate(bundle) for bundle in bundles]

This will perform the serialization.

Resource.serialize(None, data, 'application/json'),


来源:https://stackoverflow.com/questions/13565975/convert-a-queryset-to-json-using-tastypie-resource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!