Tastypie:我想要获得像“/ places / {PLACE_ID”/ comments“但是怎么样? [英] Tastypie: I want to get items like "/places/{PLACE_ID}/comments" but how?

查看:112
本文介绍了Tastypie:我想要获得像“/ places / {PLACE_ID”/ comments“但是怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



/ places / {PLACE_ID} / comments



如何用TastyPie做这个?

解决方案

按照 Tastypie的文档,并将这样添加到您的位置资源:

  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))
除了ObjectDoesNotExist:
return HttpGone()
除了MultipleObjectsReturned:
return HttpMultipleChoices(多个资源e)找到这个URI。)

#从Place
评论= obj.comments的实例获取注释#Place模型中的字段名称

#根据注释准备HttpResponse
return self.create_response(请求,注释)
#...

这个想法是您在 / places / {PLACE_ID} / comments URL和您的资源的方法之间定义一个url映射(在这个例子中 get_comments())。该方法应该返回一个 HttpResponse 的实例,但是您可以使用Tastypie提供的方法来执行所有处理(由 create_response())。我建议您查看 tastypie.resources 模块,看看Tastypie如何处理请求,特别是列表。


Let's say I want to get comments about a place. I want to make this request:

/places/{PLACE_ID}/comments

How can I do this with TastyPie?

解决方案

Follow the example in Tastypie's docs and add something like this to your places resource:

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

The idea is that you define a url mapping between the /places/{PLACE_ID}/comments URL and a method of your resource (get_comments() in this example). The method should return an instance of HttpResponse but you can use methods offered by Tastypie to do all the processing (wrapped by create_response()). I suggest you take a look at tastypie.resources module and see how Tastypie processes requests, in particular lists.

这篇关于Tastypie:我想要获得像“/ places / {PLACE_ID”/ comments“但是怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆