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)
| 归档时间: |
|
| 查看次数: |
27744 次 |
| 最近记录: |