假设我想得到关于某个地方的评论.我想提出这个要求:
/地/ {} PLACE_ID /评论
我怎么能用TastyPie做到这一点?
kgr*_*kgr 11
按照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)
# ...
Run Code Online (Sandbox Code Playgroud)
我们的想法是在/places/{PLACE_ID}/commentsURL和资源方法之间定义URL映射(get_comments()在本例中).该方法应返回一个实例,HttpResponse但您可以使用Tastypie提供的方法进行所有处理(包装create_response()).我建议你看看tastypie.resources模块,看看Tastypie如何处理请求,特别是列表.