首页 > 解决方案 > Django 休息框架。设置动态路由

问题描述

我正在为博客设置 API。我为帖子配置了评论的输出这是我的views.py的一部分,带有@action

网址.py

router = DefaultRouter()
router.register('api/posts', APIPost)

urlpatterns = [
    path('', include(router.urls)),
]

视图.py

...
    @action(methods=['get'], detail=True)
    def comments(self, request, pk=None):
        if request.method == 'GET':
            queryset = Comment.objects.filter(post__id=pk)
            serializer = CommentSerializer(queryset, many=True)
            return Response(serializer.data)
        return Response(status=status.HTTP_403_FORBIDDEN)

现在我可以在一个帖子上获得所有评论。

http://127.0.0.1:8000/api/posts/{post_pk}/comments/

问题是我只是不知道如何在

http://127.0.0.1:8000/api/posts/{post_pk}/comments/{comment_pk}

我不断收到“404 Not Found”错误

标签: python-3.xdjango-rest-frameworkaction

解决方案


您应该创建另一个CommentViewSet. (文档

视图.py

from rest_framework import viewsets

class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

网址.py

from .views import CommentViewSet

router = DefaultRouter()
router.register("api/posts", APIPost)
router.register("api/comments", CommentViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

然后您可以通过向http://127.0.0.1:8000/api/comments/{pk}.


此外,在您的代码中,

  1. @action(methods=['get'], detail=True)相反,它应该是@action(methods=['get'], detail=False)因为该comments操作是检索所有评论的列表。detail=True用于返回单个对象。
  2. 您不需要手动检查,if request.method == 'GET'因为 DRF 已经在内部执行此操作,因为您已经指定了methods=["get"].

推荐阅读