问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/12877437/tastypie-i-want-to-get-items-like-places-place-id-comments-but-how