Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Routers and URLs

Nested and Related Routes

Design nested URLs like /authors/1/books/ in Django REST Framework: filter by the parent, create children with the parent set, return 404 for missing parents, and know the alternatives.

Resources often belong to other resources: an author's books, a project's tasks, an order's lines. REST APIs express that with nested URLs such as /authors/3/books/ (the books of author 3) and /authors/3/books/12/ (one of them). DRF's routers do not generate nested URLs themselves, but a few lines of code do the job well, and you stay in control of the rules.

This lesson builds a nested resource by hand, shows how to keep parent and child consistent, and compares nesting with flat URLs and with @action.

Nesting by hand with a viewset

The trick: register the child viewset on a URL that includes the parent id, and let get_queryset() and perform_create() read that id from self.kwargs.

Python Books nested under an author

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four rules make this safe:

  1. Filter the queryset by the parent. get_object() searches get_queryset(), so /authors/2/books/1/ is a 404 even though book 1 exists. Without the filter, any author id in the URL would reach any book.
  2. Fetch the parent with get_object_or_404. An unknown author gives a clear 404 instead of an empty list. An empty list would wrongly suggest the author exists and merely has no books.
  3. Set the foreign key on the server. perform_create writes author from the URL; the serializer does not accept it, so a client cannot create a book under a different author than the URL says.
  4. Reject mismatches, do not ignore them. If a serializer does accept the parent field, validate that it equals the URL's value.

Authorization comes with the same pattern: check the parent against the user in get_author() (for example get_object_or_404(Author.objects.filter(owner=self.request.user), ...)), and every action inherits the rule.

Routing the nested viewset

Because the URLs carry an extra keyword (author_pk), the standard routers cannot generate them. You have three options:

  • Write two path() lines with as_view({...}) mappings, as above. Plain, explicit and enough for most projects.
  • Use a router per parent. Build a small router inside a function, or give a router a custom lookup prefix.
  • Use the third-party drf-nested-routers package, which adds NestedSimpleRouter(parent_router, "authors", lookup="author") and generates authors/{author_pk}/books/. It saves lines when you nest several resources, at the cost of one more dependency.
Python
# drf-nested-routers (third-party; shown read-only, not run on this site)
from rest_framework_nested import routers

router = routers.SimpleRouter()
router.register("authors", AuthorViewSet)

authors_router = routers.NestedSimpleRouter(router, "authors", lookup="author")
authors_router.register("books", AuthorBookViewSet, basename="author-books")

urlpatterns = router.urls + authors_router.urls

An alternative: a custom action on the parent

When the child list is read-mostly and always belongs to one parent, a list action on the parent viewset is lighter than a second viewset:

Python A books action on the author viewset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This version has no per-book URL (/authors/1/books/5/). If clients need to read, update or delete single books, a nested viewset or a flat /books/ endpoint is the better fit.

Flat alternative: filter by query string

Many mature APIs avoid deep nesting and use a flat endpoint with a filter: /books/?author=1. Compare:

Style Example Strengths Weaknesses
Nested /authors/1/books/12/ Shows ownership, easy parent-scoped permissions Long URLs, an id for each level, duplicated routing code
Flat + filter /books/12/ and /books/?author=1 One URL per resource, easy caching, works with filter backends Parent is a parameter, permission checks live in the child viewset

A common rule of thumb: nest one level when the child cannot exist without its parent (an order's lines), and keep resources flat when they have an independent life (books can move between authors). Avoid nesting deeper than two levels; /a/1/b/2/c/3/d/ is a sign that c or d deserve their own top-level URL.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why filter the child queryset by the parent id?

    get_object() searches the filtered queryset, so a child that does not belong to the parent in the URL gives a 404.
  2. 2. How should the parent foreign key be set when creating a nested child?

    Server-side assignment from the URL keeps the URL and the stored data consistent.
  3. 3. What does get_object_or_404 on the parent give you that an empty list does not?

    An empty list would look like a valid parent with no children.
  4. 4. When is a flat endpoint like /books/?author=1 a good choice?

    Independent resources work well flat; nesting suits children that cannot exist without their parent.

Summary

  • Nested URLs such as /authors/1/books/ need the parent id in self.kwargs, used by get_queryset() and perform_create().
  • Always filter children by the parent, fetch the parent with a 404, and set the foreign key on the server.
  • Routers do not generate nested URLs: write two path() lines, or use drf-nested-routers.
  • A custom @action on the parent is a lightweight alternative for simple child lists.
  • Prefer one level of nesting; use flat URLs with filters for independent resources.

Next: Authentication Schemes in DRF