问题
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