1

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?

1 Answer 1

3

Actually that's exactly what you should return. I recommend that you take a look at Tastypie's implementation of obj_get:

 def obj_get(self, request=None, **kwargs):
    """
    A ORM-specific implementation of ``obj_get``.

    Takes optional ``kwargs``, which are used to narrow the query to find
    the instance.
    """
    try:
        base_object_list = self.get_object_list(request).filter(**kwargs)
        object_list = self.apply_authorization_limits(request, base_object_list)
        stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in kwargs.items()])

        if len(object_list) <= 0:
            raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))
        elif len(object_list) > 1:
            raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))

        return object_list[0]
    except ValueError:
        raise NotFound("Invalid resource lookup data provided (mismatched type).")

As you can see they use self.get_object_list to obtain a list of items meeting the criteria (in this case kwargs should contain pk) 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_get should 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 in RiakObject class so that instead of obj[ 'attribute' ] you can do obj.attribute which 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 RiakObject mentioned above. I don't recommend the latter though in case of Django :)

Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.