繁体   English   中英

如何在使用 DRF Viewset 的操作方法时在 api 的末尾添加 {id} 查找

[英]How to add {id} lookup at the end of api while using DRF Viewset's action method

基本上,我希望在 api 末尾有 {id} 条评论。来自

http://localhost:8000/articles/{id}/comments/ 

http://localhost:8000/articles/{id}/comments/{id}/

class ArticlesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet
):
    queryset = Articles.objects.order_by("-created")
    serializer_class = ArticlesSerializer

    @action(methods=["delete"], detail=True)
    def comments(self, request, *args, **kwargs):
        # do something

网址.py

v1_router = routers.DefaultRouter()
v1_router.register(r"articles", ArticleViewSet)

urlpatterns = [path("v1/", include(v1_router.urls))]

如何使 url 如上所述?

对于仍然有兴趣知道我是如何解决这个问题的人,

    @action(
        detail=True,
        methods=["post"],
        url_path="comments/(?P<comment_id>[^/.]+)",
    )
    def comments(self, request, comment_id):
        # you can continue here with rest of the code

现在你可以像 api

http://localhost:8000/articles/{id}/comments/{id}/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM