Tastypie: I want to receive items like "/ places / {PLACE_ID] / comments", but how?

Say I want to get comments about the place. I want to make this request:

/ places / {PLACE_ID} / comments

How can I do this with TastyPie?

+4
source share
1 answer

Follow the example of Tastypie docs and add something like this to the 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 between the URL /places/{PLACE_ID}/comments and the method of your resource ( get_comments() in this example). The method should return an HttpResponse instance, but you can use the methods suggested by Tastypie to do all the processing (wrapped with create_response() ). I suggest you take a look at the tastypie.resources module and see how Tastypie handles requests, in particular lists.

+11
source

Source: https://habr.com/ru/post/1439586/


All Articles