python-3.x - 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”错误
解决方案
您应该创建另一个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}
.
此外,在您的代码中,
@action(methods=['get'], detail=True)
相反,它应该是@action(methods=['get'], detail=False)
因为该comments
操作是检索所有评论的列表。detail=True
用于返回单个对象。- 您不需要手动检查,
if request.method == 'GET'
因为 DRF 已经在内部执行此操作,因为您已经指定了methods=["get"]
.
推荐阅读
- wcf - wcf 托管在 Windows 服务和 httpbindings 中
- vba - Outlook 中用于密码保护附件文件的 VBA 插件
- javascript - 有没有办法使用 AJAX 将响应结果传递到另一个页面
- angular - Angular 和 FabricJS 类变量和事件
- c - 如何将另一个模块中的变量发送给函数?
- java - 在类型 [com.modelimpl.Modelmvcimpl] 上找不到属性 [fname]
- java - 尝试通过 JSON 查询从 openweathermap 获取数据时出现 FileNotFoundException
- excel - 直到循环执行缓慢 - 偏移和选择的替代方案?
- android - 查找设备的运动
- javascript - 如何使用 Selenium 进行硬刷新