19

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i see, so i've to use a plugin. but in the child, how can i init the field that refences the main father. For example, i've instance.task, how can i set it in a way that is as the one of the url? i've to override the pre_save()?
Also asking for that, how can one in the NestedViewSet get the object of the parent, I didn't find the pk in the kwargs, or am I missing something?
github.com/kevin-brown/drf-nested-viewsets is archived and 8 years have passed since you gave this answer. Do you mind adding an update?
13

DRF extensions also provides a way to create nested routes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.