假设这个网址:
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/