使用tastypie资源将queryset转换为json [英] Convert a queryset to json using tastypie resource

查看:228
本文介绍了使用tastypie资源将queryset转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模特的tastypie资源。我还有一个看法,需要一个需要序列化并发送给客户端的查询器。我正在寻找一种方法来让味美资源处理查询的序列化和脱水。



我看到我可以传递一个对象到

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

创建一个捆绑包,然后将捆绑包传递给

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

,最后调用

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

对脱水数据。



但是,我想将完整的查询器转换为json而不仅仅是一个对象。也许我需要的是一种将完整的查询器转换为捆绑的方法。



任何帮助都赞赏!

解决方案

这也是我的错,但是我想在github上查看tastypie的代码后,我找到了答案。



这将使一堆的捆绑包。

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

这将执行脱水。

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

将执行序列化。

  Resource.serialize(无,数据,'application / json'),


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!

解决方案

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'),

这篇关于使用tastypie资源将queryset转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆