4

假设我想获得关于某个地方的评论。我想提出这个要求:

/places/{PLACE_ID}/评论

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

4

1 回答 1

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}/commentsURL 和资源的方法之间定义一个 url 映射(get_comments()在此示例中)。该方法应该返回一个实例,HttpResponse但您可以使用 Tastypie 提供的方法来完成所有处理(由 包装create_response())。我建议你看一下tastypie.resources模块,看看 Tastypie 如何处理请求,特别是列表。

于 2012-10-15T08:03:04.227 回答