Tastypie:我想就像“/地/ {} PLACE_ID /评论”,但怎么样的项目?(Tastyp

2019-08-01 10:34发布

比方说,我想获得一个地方的意见。 我想提出这个要求:

/地/ {} PLACE_ID /评论

我如何与TastyPie做到这一点?

Answer 1:

按照该示例Tastypie的文档 ,并添加像这样到您的places资源:

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)           
     # ...

这个想法是,你定义之间的URL映射/places/{PLACE_ID}/comments网址和资源的方法( get_comments()在这个例子中)。 该方法应该返回的实例HttpResponse ,但你可以使用Tastypie提供给所有的处理方法(由包裹create_response() 我建议你看一看tastypie.resources模块,看看Tastypie如何处理请求,尤其名单。



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