5

I want to implement routes like this:

/items - list of all items.
/items/types - list of all item types

I was looking at drf-nester-routs, but nested urls expect {pk} to be passed. Is there any good way to achieve what i want?

mcferden
  • 316
  • 3
  • 11

2 Answers2

3

If you do not need pk, then your route should be /types not /items/types

You may need to take a look at this SO question about REST nested resources:

What are best practices for REST nested resources

Community
  • 1
  • 1
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • 1
    Right now it is implemented in this way. But I think it's more logical to make types sub-url of items because they are types of items and nothing else. – mcferden Dec 05 '16 at 09:13
  • 1
    If they are types of items (sub-resources of items) that means you need to add `pk`. If I understand well what you need is `/types` not `/items//types` – ettanany Dec 05 '16 at 09:14
1

With ID /items/1/types would mean something like "display all types belonging to the item with id 1". Whereas /items/types doesn't really make sense because resource types can't belong to all item resources.

However, you could implement it, as a custom action for your ViewSet using @list_route decorator, e.g.

class MyViewSet(viewsets.ModelViewSet):
    ...
    @list_route()
    def types(self, request):
        return Response(some_way_to_list_types())
    ...

It's probably not a RESTful way though.

Docs on custom ViewSet actions

CrowbarKZ
  • 1,203
  • 11
  • 18