Convert a queryset to json using tastypie resource
Asked Answered
B

1

8

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!

Battlement answered 26/11, 2012 at 13:37 Comment(0)
B
10

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'),
Bordie answered 28/11, 2012 at 8:45 Comment(1)
Thanks. I've managed to adapt this to a specical case where instead of a queryset, you have a single model instance for example. Check https://mcmap.net/q/1328233/-how-to-convert-a-django-model-instance-to-json-using-existing-tastypie-resourcePanchito

© 2022 - 2024 — McMap. All rights reserved.