假设我想收到有关某个地方的评论。我想提出这个要求:
/地点/ {PLACE_ID} /评论
我怎么能用TastyPie做到这一点?
答案 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如何处理请求,特别是列表。