0

我尝试使用他们提供的两个示例在 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)

现在我的具体用例是拥有类似的 URL /api/v1/schools/<school_id>/departments,它会做什么,是获取departments属于school具有特定 ID 的列表。如果学校有 1 个部门,一切正常,但是如果学校有 2 个以上部门,我会收到错误消息More than one resource is found at this URI.

TastyPie 在传递资源 ID 时是否不支持资源列表,或者我该如何解决这个问题?

4

1 回答 1

1

你只需要更换

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

经过

return child_resource.get_list(request, parent_id=obj.pk)
于 2014-02-13T18:51:19.220 回答