如何使用现有的Tastypie资源将Django模型实例转换为JSON? [英] How to convert a Django model instance to JSON using existing Tastypie Resource?

查看:66
本文介绍了如何使用现有的Tastypie资源将Django模型实例转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与其他问题有关,但是相反,我希望使用现有的Tastypie资源将单个模型实例转换为JSON.

This problem is related to this other problem, but instead, I wish to convert a single model instance to JSON, using an existing Tastypie Resource.

推荐答案

感谢@grimygoop的提示,我设法创建了一种方法,该方法可以使用关联的Tastypie资源将任何Django模型实例序列化为JSON.这是程序的工作方式...

Thanks to @grimygoop for the hint, I managed to create a method that can serialize any Django model instance to JSON using the associated Tastypie Resource. Here's how the procedure works...

def res_serialize(request, resource, obj):
    data = resource.full_dehydrate(resource.build_bundle(obj=obj, request=request))
    return resource.serialize(None, data, 'application/json')

要使用此功能,您必须已经定义了Resource类,并且还必须具有一个请求对象,此功能才能按预期工作.然后,您将像这样执行序列化:

To use this, you must have already defined a Resource class, and must also have a request object for this to work as expected. You'd then perform the serialization as such:

res_serialize(request,ClientResource(),client)

注意上述调用中的 ClientResource()-我们必须传递Resource实例,而不仅仅是类引用.因此,在上面的示例中,对象 client 通过关联的资源类被序列化为JSON.例如,这可以在希望返回对象的序列化实例的自定义视图中提供帮助.

Note ClientResource() in the invocation above - we must pass the Resource instance, not just the class reference. So, in the above example, the object client gets serialized to JSON via the associated resource class. This can for example help in custom views where you wish to return a serialized instance of the object.

此外,对此稍作修改就可以处理查询集而不是单个对象.

Also, a slight modification of this can handle querysets instead of single objects.

这篇关于如何使用现有的Tastypie资源将Django模型实例转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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