2013-08-21 158 views
0

我試着在TastyPie中使用它們提供的兩個示例實現嵌套資源。其中一個失敗了,我不知道如何或爲什麼,其中一個有點作用。TastyPie中的嵌套資源

這是剪斷我使用的代碼:

class ParentResource(ModelResource): 
    children = fields.ToManyField(ChildResource, 'children') 

    def prepend_urls(self): 
     return [ 
      url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/children%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_children'), name="api_get_children"), 
     ] 

    def get_children(self, request, **kwargs): 
     try: 
      bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request) 
      obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) 
     except ObjectDoesNotExist: 
      return HttpGone() 
     except MultipleObjectsReturned: 
      return HttpMultipleChoices("More than one resource is found at this URI.") 

     child_resource = ChildResource() 
     return child_resource.get_detail(request, parent_id=obj.pk) 

現在我的具體使用情況是有像/api/v1/schools/<school_id>/departments URL和這是什麼要做的,就是讓屬於schooldepartments列表帶有一定的ID。如果學校有一個部門,一切正常,但是如果學校有2+部門,我得到錯誤信息More than one resource is found at this URI.

TastyPie在傳遞資源ID時不支持資源列表,或者我該如何解決這個問題?

回答

1

您只需要更換

return child_resource.get_detail(request, parent_id=obj.pk) 

通過

return child_resource.get_list(request, parent_id=obj.pk)