Tastypie:我想获得像“/ places / {PLACE_ID} / comments”这样的项目,但是怎么样?

时间:2012-10-13 22:06:19

标签: django tastypie

假设我想收到有关某个地方的评论。我想提出这个要求:

/地点/ {PLACE_ID} /评论

我怎么能用TastyPie做到这一点?

1 个答案:

答案 0 :(得分:11)

按照Tastypie's docs中的示例操作,并在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)           
     # ...

您的想法是在/places/{PLACE_ID}/comments网址和资源方法(本例中为get_comments())之间定义网址映射。该方法应返回HttpResponse的实例,但您可以使用Tastypie提供的方法进行所有处理(由create_response()包装)。我建议你看看tastypie.resources模块,看看Tastypie如何处理请求,特别是列表。