在django-rest-framework中捕获参数

bil*_*Joe 41 django django-rest-framework

假设这个网址:

http://localhost:8000/articles/1111/comments/
Run Code Online (Sandbox Code Playgroud)

我想获得给定文章的所有评论(这里是1111).

这是我捕获这个网址的方式:

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

相关视图看起来像:

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
Run Code Online (Sandbox Code Playgroud)

有关信息,请参阅相关序列化程序

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

    class Meta:
        model = Comment
        fields = ('id', 'content', 'owner', 'created_at')
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我已经更新了我的get_queryset来过滤关于文章的评论,但我不知道如何捕获"uid"参数.使用以?uid = value结尾的url,我可以使用self.request.QUERY_PARAMS.get('uid')但在我的情况下我不知道该怎么做.一个主意 ?

Sco*_*all 63

url参数存储在self.kwargs.lookup_field是查找单个模型实例时通用视图在ORM中使用的字段(默认为pk),lookup_url_kwarg可能是您想要的属性.

请尝试以下方法:

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
Run Code Online (Sandbox Code Playgroud)

  • 嘿@Scott Woodall,我遇到了类似的问题,现在我解决了。我现在关心的是,这个“lookup_url_kwarg”是必须的吗?如果我有多个参数怎么办?例如`uid`,`some_thing_else`?这样做可以吗 `comments = Comment.objects.filter(article=self.kwargs.get('uid'))` ? (3认同)