我想创建两个端点/comments/
和/comments/requests/
或类似的东西。第一个显示您的评论,第二个显示您的待处理评论(人们发送给您的评论,您需要批准)。他们都使用评论模型。我怎样才能在Django Rest Framework中实现这一目标?
现在,我的观点是
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
来切换端点的行为,但这看起来似乎很草率。
答案 0 :(得分:1)
使用list_route装饰器和genericviewset
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和ViewSet文档