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

爱⌒轻易说出口 提交于 2019-12-05 02:04:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!