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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With