How to convert a Django model instance to JSON using existing Tastypie Resource?

ぃ、小莉子 提交于 2019-12-25 00:28:51

问题


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.


回答1:


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

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)

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.



来源:https://stackoverflow.com/questions/56089256/how-to-convert-a-django-model-instance-to-json-using-existing-tastypie-resource

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