73

suppose this url:

http://localhost:8000/articles/1111/comments/

i'd like to get all comments for a given article (here the 1111).

This is how i capture this url:

url(r'^articles/(?P<uid>[-\w]+)/comments/$', comments_views.CommentList.as_view()),

The related view looks like to:

class CommentList(generics.ListAPIView):    
    serializer_class = CommentSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    lookup_field = "uid"

    def get_queryset(self):
        comments = Comment.objects.filter(article= ???)
        return comments

For information, the related serializer

class CommentSerializer(serializers.ModelSerializer):
    owner = UserSerializer()

    class Meta:
        model = Comment
        fields = ('id', 'content', 'owner', 'created_at')

As you can see, I've updated my get_queryset to filter comments on the article but I don't know how to catch the "uid" parameter. With an url ending with ?uid=value, i can use self.request.QUERY_PARAMS.get('uid') but in my case, I don't know how to do it. Any idea?

TheSohan
  • 442
  • 3
  • 18
billyJoe
  • 2,034
  • 2
  • 24
  • 37

1 Answers1

101

The url parameter is stored in self.kwargs. lookup_field is the field (defaults to pk) the generic view uses inside the ORM when looking up individual model instances, lookup_url_kwarg is probably the property you want.

So try the following:

class CommentList(generics.ListAPIView):    
    serializer_class = CommentSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    lookup_url_kwarg = "uid"

    def get_queryset(self):
        uid = self.kwargs.get(self.lookup_url_kwarg)
        comments = Comment.objects.filter(article=uid)
        return comments
Scott Woodall
  • 10,456
  • 6
  • 39
  • 37
  • 1
    thanks !! i've tried unsuccessfully to build a custom mixins (http://www.django-rest-framework.org/api-guide/generic-views#customizing-the-generic-views) but your solution works fine. :) – billyJoe Jan 22 '14 at 21:20
  • 1
    You may want to explore this library which takes `query params` and put filters on `queryset` in an elegant way. https://github.com/manjitkumar/drf-url-filters – Manjit Kumar Apr 09 '16 at 21:27
  • 3
    Hey @Scott Woodall, I had a similar problem, now I sorted it out. My concern here now is, is this `lookup_url_kwarg` a must? How about if I I'm having multiple params? e.g `uid`, `some_thing_else`? Is it ok to just do this way `comments = Comment.objects.filter(article=self.kwargs.get('uid'))` ? – Wafula Samuel Mar 11 '18 at 15:43