Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework nested viewsets and routes

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.

like image 891
EsseTi Avatar asked May 05 '14 15:05

EsseTi


2 Answers

DRF extensions also provides a way to create nested routes.

like image 51
ybendana Avatar answered Sep 21 '22 14:09

ybendana


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.

like image 43
Kevin Brown-Silva Avatar answered Sep 17 '22 14:09

Kevin Brown-Silva