假设URL为:

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

我想知道某篇文章(这里是1111)的所有 comments .

下面是我捕获此url的方式:

url(r'^articles/(?P<uid>[-\w]+)/comments/$', comments_views.CommentList.as_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更新为对文章的过滤 comments ,但是我不知道如何捕捉"uid"参数. 如果url以?uid=value结尾,我可以使用self.request.QUERY_PARAMS.get(‘uid’),但在我的例子中,我不知道怎么做. 有什么 idea 吗?

推荐答案

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

因此,请try 以下操作:

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命令中的no_color不起作用

Django为什么我的post.count_view递增2?

在Django中提交表单后更改模型数据

如何在Django管理自定义筛选器中包含自定义模型方法?

Django prefetch_related 与 3 个不直接相关的模型

Django 获取用户创建的对象,这些用户属于用户列表

如何在 createsuperuser 中实例化表

Nginx 响应 404 not found on Django media URL in preprod, dev ok

Django ORM:获取每个类别的月平均价格

Django - 使用在 URL 中传递的父类主键从子类中过滤对象

如何在 Django 中将下一个 8 月 1 日添加为 DateTimeField 默认值

将计数字段添加到 django rest 框架序列化程序

如何在不使用 sudo 的情况下安装 virtualenv?

如何在Django中获取一个组的所有用户?

在 django 模板中访问元组

如何使用 django-nose 运行单个测试或单个 TestCase?

在 Django 中测试different layers的最佳实践是什么?

Django模板转换为字符串

Django - TypeError - save() 得到了一个意外的关键字参数force_insert

Django: Force强制 Select 相关?