Capture parameters in django-rest-framework

后端 未结 1 1780
长发绾君心
长发绾君心 2021-01-30 06:21

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

1条回答
  •  温柔的废话
    2021-01-30 07:14

    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
    

    0 讨论(0)
提交回复
热议问题