Django Rest Framework - detail page of @detail_route

后端 未结 2 838
滥情空心
滥情空心 2021-01-18 20:11

I am ussing @detail_route on my viewsets.ModelViewSet.

class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class         


        
相关标签:
2条回答
  • 2021-01-18 20:48

    DRF does not handle nested routes by itself, you may handle it by hand or use an extension, like drf-nested-routers, but its outdated.

    My advice : don't fight the framework, DRF is not good at playing with url-nested resources, do it another way.

    0 讨论(0)
  • 2021-01-18 20:49

    So avoid it when you can...but sometimes it makes sense to nest resources or methods

    So for your case to handle both the accounts/ url and accounts/{account_id} you define another detail route.

    You have already defined the one for accounts so you just add another function with a different name and ensure to add the url_path so you can get the account_id variable.

            @detail_route(methods=['get', ], permission_classes=[IsCompanyUserPermission, ])
            def accounts(self, request, pk):
            ...
            return Response(...)
    
            @detail_route(methods=['get', ], permission_classes=[IsCompanyUserPermission, ], 
                          url_path='^queues/(?P<account_id>[0-9]+)')
            def account_detail(self, request, pk, account_id):
            ...
            return Response(...)
    

    This answer took this similar answer as a reference

    0 讨论(0)
提交回复
热议问题