Django rest fram中同一资源的两个端点

2024-06-25 07:11:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建两个端点/comments/和{}或类似的东西。第一个显示您的评论,第二个显示您的待定评论(人们向您发送的需要您批准的评论)。它们都使用注释模型。如何在Django Rest框架中实现这一点?在

现在,我的观点是

class CommentsListview(APIView):
    serializer_class = CommentSerializer
    def get(self, request, format=None):
        comments, _, _, = Comments.get_comment_users(request.user)
        comments_serializer = CommentSerializer(comments, many=True)
        return Response({'comments': comments_serializer.data})

    def requests(sel,f request, format=None):
        _, requests, _ = Comments.get_comment_users(request.user)
        requests_serializer = CommentSerializer(requests, many=True)
        return Response({'requests': requests_serializer.data})

我想允许用户转到localhost:8000/comments/查看他们的评论,localhost:8000/comments/requests/来查看他们的未决评论请求。因为我还没有弄清楚这个问题,唯一的解决方案是要求用户使用参数作为标志/comments/?requests=True来切换端点的行为,但这看起来太草率了。在


Tags: nonetrueformatgetrequestdefcomment评论
1条回答
网友
1楼 · 发布于 2024-06-25 07:11:29

路由和使用集合

from rest_framework import viewsets
from rest_framework.decorators import list_route

class CommentsListview(viewsets.GenericViewSet):
    serializer_class = CommentSerializer

    def list(self, request, format=None):
        comments, _, _, = Comments.get_comment_users(request.user)
        comments_serializer = CommentSerializer(comments, many=True)
        return Response({'comments': comments_serializer.data})

    @list_route()
    def requests(sel,f request, format=None):
        _, requests, _ = Comments.get_comment_users(request.user)
        requests_serializer = CommentSerializer(requests, many=True)
        return Response({'requests': requests_serializer.data})
  • /comments/将调用list方法
  • /comments/requests/将调用requests方法

另请看GenericViews和{a2}文档,这可能会有帮助

相关问题 更多 >