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

1

0

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.

Glossotomy answered 11/5, 2019 at 10:8 Comment(0)
G
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.

Glossotomy answered 11/5, 2019 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.