在Django-rest-framework中捕获参数 [英] Capture parameters in django-rest-framework
问题描述
假设此网址:
http://localhost:8000/articles/1111/comments/
我想获取给定文章的所有评论(此处为1111)。
i'd like to get all comments for a given article (here the 1111).
这就是我捕获的方式该网址:
This is how i capture this 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
有关信息,请参见相关的序列化器
For information, the related serializer
class CommentSerializer(serializers.ModelSerializer):
owner = UserSerializer()
class Meta:
model = Comment
fields = ('id', 'content', 'owner', 'created_at')
如您所见,我已经更新了get_queryset以过滤对文章的评论,但我不知道如何捕捉 ; uid参数。
使用以?uid = value结尾的网址,我可以使用self.request.QUERY_PARAMS.get(‘uid’),但就我而言,我不知道该怎么做。
有什么想法吗?
As you can see, I've updated my get_queryset to filter comments on the article but I don't know how to catch the "uid" parameter. With an url ending with ?uid=value, i can use self.request.QUERY_PARAMS.get('uid') but in my case, I don't know how to do it. Any idea?
推荐答案
url参数存储在 self.kwargs $中c $ c>。
lookup_field
是通用视图在查找单个模型实例时在ORM中使用的字段(默认为pk), lookup_url_kwarg
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
这篇关于在Django-rest-framework中捕获参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!