Django rest framework nested viewsets and routes

后端 未结 2 2076
误落风尘
误落风尘 2021-02-19 16:03

Can i nest the viewsets and create routes that takes pk as parameters of the url?

basically:

class TaskView(viewsets.ModelViewSet):
    mode         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 16:42

    There are two plugins out there for making this happen: drf-nested-viewsets and drf-nested-routers.

    DRF Nested Routers works on a router level and makes it easy to do nested viewsets, as the nested parameters are passed into every method for easy reference. The README in the repository gives an overview of what can be done. This does not appear to allow for nested DefaultRouters (which include the API root page).

    DRF Nested Viewsets (full disclosure: created by me) is primarily meant for hyperlinked scenarios (where everything uses a HyperlinkedModelSerializer) and isn't as easy to use. It handles hyperlinked relations by mapping the current URL arguments to generate nested urls on linked models. A bit of documentation is available at the original gist.

    Both plugins require overriding get_queryset for filtering nested querysets. For DRF Nested Viewsets this requires pulling url arguments from self.kwargs within the viewset and using those to filter, I am not sure how it is done using DRF Nested Routers, but it mostly likely isn't much different.

    Note: If you do not need hyperlinked relations, this can be done without third-party plugins by just overriding get_queryset and filtering off of url arguments.

提交回复
热议问题