返回Django对Tastypie资源的评论

Roa*_*ter 5 django django-comments tastypie

我的Django网站有一个Photo模型,代表系统中的照片,我用它Django.contrib.comments来允许用户评论这些.这一切都运行正常,但我想扩展我的Tastypie API,以允许我PhotoResource使用URL 访问评论,例如/api/v1/photo/1/comments1是照片的ID.我能够让URL工作正常,但无论我正在做什么样的过滤,我似乎总是返回完整的注释集,而不仅仅是提供的照片集.我在下面列出了我当前代码API的精选内容:

class CommentResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')
    class Meta:
       queryset = Comment.objects.all()
            filtering = {
                'user': ALL_WITH_RELATIONS,
            }

class PhotoResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')  
    class Meta:
        queryset = Photo.objects.all()
        filtering = {
            'id': 'exact',
            'user': ALL_WITH_RELATIONS
        }

    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.")
        comment_resource = CommentResource()
        return comment_resource.get_list(request, object_pk=obj.id, content_type=ContentType.objects.get_for_model(Photo))
Run Code Online (Sandbox Code Playgroud)

据我所知,最后一行中的过滤器无效.我认为这有点复杂,因为contrib.com使用ContentTypes链接到被评论的对象,我猜Tastypie可能无法应对.我已经尝试了很多变种,但它仍然无法正常工作.我觉得这样的事情会起作用:

ctype = ContentType.objects.get_for_model(obj)
comment_resource = CommentResource()
return comment_resource.get_list(request, object_pk=obj.pk, content_type_id=ctype.id)
Run Code Online (Sandbox Code Playgroud)

但所有评论都被归还了.

有没有人有任何想法如何做到这一点(或者甚至可能)?

end*_*dre 1

通常,我不会将其侵入 PhotoResource,而是会在 CommentResource 中进行过滤。您必须为该模型启用过滤,并且 url 将如下所示:

/api/v1/comment/?object__pk=1&content_type_id=2