Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Django comments for a Tastypie resource

My Django site has a Photo model which represents photos in the system and I'm using Django.contrib.comments to allow users to comment on these. This is all working fine but I'd like to extend my Tastypie API to allow accessing of comments for my PhotoResource using a URL like /api/v1/photo/1/comments where 1 is the id of the photo. I'm able to get the URL to work fine but no matter what sort of filtering I'm doing I always seem to return the complete set of comments rather than just the set for the supplied photo. I've included a cut down selection of my current code API below:

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

As far as I can tell it's the filter in the last line that isn't working. I think this is slightly complicated due to contrib.comments using ContentTypes to link to the object being commented on which I guess it's possible Tastypie can't cope with. I've tried a bunch of variations on this but it still doesn't work. I felt pretty certain something like this would work:

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)

but again all comments were returned.

Does anyone have any ideas how to do this (or if it's even possible)?

like image 995
Roarster Avatar asked Nov 14 '22 02:11

Roarster


1 Answers

Usually instead of hacking it into the PhotoResource I would do a filtering in the CommentResource instead. You have to enable filtering for that model and the url would look like this:

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

like image 178
endre Avatar answered Dec 24 '22 09:12

endre