Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tastypie: I want to get items like "/places/{PLACE_ID}/comments" but how?

Let's say I want to get comments about a place. I want to make this request:

/places/{PLACE_ID}/comments

How can I do this with TastyPie?

like image 778
Burak Avatar asked Dec 20 '22 15:12

Burak


1 Answers

Follow the example in Tastypie's docs and add something like this to your places resource:

class PlacesResource(ModelResource):

    # ...

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/comments%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_comments'), name="api_get_comments"),
    ]

    def get_comments(self, request, **kwargs):
        try:
            obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices("More than one resource is found at this URI.")

        # get comments from the instance of Place 
        comments = obj.comments # the name of the field in "Place" model

        # prepare the HttpResponse based on comments
        return self.create_response(request, comments)           
     # ...

The idea is that you define a url mapping between the /places/{PLACE_ID}/comments URL and a method of your resource (get_comments() in this example). The method should return an instance of HttpResponse but you can use methods offered by Tastypie to do all the processing (wrapped by create_response()). I suggest you take a look at tastypie.resources module and see how Tastypie processes requests, in particular lists.

like image 51
kgr Avatar answered Mar 19 '23 05:03

kgr