I have to implement a new ModelResource that overrides the original obj_get method. What kind of object do I have to return? An instance of a Django model? It’s not explained well in the Tastypie documentation. Let’s say I have a Django model I want to return turn into json and send back to whoever did the GET request. How is it normally implemented?
I have this code:
def obj_get(self, request=None, **kwargs):
return Item.objects.get(id=kwargs['pk'])
It’s just to show you what I am trying to do. I have figured out that it’s not a Django instance that I have to return. What do I have to return?
Actually that’s exactly what you should return. I recommend that you take a look at Tastypie’s implementation of
obj_get:As you can see they use
self.get_object_listto obtain a list of items meeting the criteria (in this casekwargsshould containpk) and are hoping to get just one item. In such case they return the first (and only item on that list). Otherwise an exception is raised. The list in case of Django is simply a queryset though.In general –
obj_getshould return an object which has properties corresponding to Resource attributes. Good example of this is given in Using Riak for MessageResource where a dictionary is wrapped inRiakObjectclass so that instead ofobj[ 'attribute' ]you can doobj.attributewhich is required by Tastypie (and hence Django model instance will work).So to summarize, you can return a Django model instance, or if you’re feeling desire for some extra work and would like to worsen the performance, you could build dictionaries out of model instance attributes and wrap them in class like
RiakObjectmentioned above. I don’t recommend the latter though in case of Django 🙂Good luck!