Django rest framework nested viewsets and routes

2020-08-14 07:42发布

问题:

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

basically:

class TaskView(viewsets.ModelViewSet):
    model = Task

this works fine and it's mapped to the task/ url, so task/1/ gives the data of the task with id 1. now, i want to create an instance of the task, having CRUD operations as for the task, so i would like to have

class InstanceView(viewsets.ModelViewSet):
        model = Instance

mapped to task/{pk}/instance, where pk is the id of the task.

how can i do that? is it possible? PS: i saw that there are @action and @link but using them i loose the power of having everything made by the framework.

回答1:

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.



回答2:

DRF extensions also provides a way to create nested routes.