简体   繁体   中英

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

Basically i want {id} of comment at the end of api. from

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

to

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

urls.py

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

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

how to make url as described above?

For someone who is still interested to know how i resolved this issue was,

    @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

Now you can have api like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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