django - 在django-rest-framework中捕获参数

标签 django django-rest-framework

假设这个网址:

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

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

这就是我捕获此 url 的方式:

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

相关 View 如下所示:

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

有关信息,相关的序列化器

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

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

如您所见,我已经更新了我的 get_queryset 以过滤文章的评论,但我不知道如何捕获“uid”参数。 对于以 ?uid=value 结尾的 url,我可以使用 self.request.QUERY_PARAMS.get('uid') 但就我而言,我不知道该怎么做。 有什么想法吗?

最佳答案

url参数保存在self.kwargs中。 lookup_field 是通用 View 在查找单个模型实例时在 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

关于django - 在django-rest-framework中捕获参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292646/

相关文章:

php - 如何在使用相同域的 NGINX 服务器上运行 django 和 wordpress?

django - 使用Django REST Framework的ListCreateAPIView时如何为POST和List等不同方法设置不同的权限

authentication - django-rest-framework token 验证和注销

django - Django Rest Framework (DRF) 中的 add_error(fieldname, ...)

python - Django:自然排序查询集

sql - 我应该如何建模模型可以与 Django 中不同类型的实体相关的模式

django - 客户端补丁在 django 测试中给出 400 错误

Django模板如何对简单标签返回的结果应用过滤器

python - Django 将用户 ID 嵌入 URL 模板最佳实践

python - 在内部创建具有 jinja 结构的字符串