没有 PK 的 Django REST Framework 嵌套路由

Django REST Framework nested routes without PK

我想实现这样的路由:

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

我正在查看 drf-nester-routs,但嵌套的 url 期望 {pk} 被传递。有什么好的方法可以达到我想要的效果吗?

如果您不需要pk,那么您的路线应该是/types而不是/items/types

您可能需要查看有关 REST 嵌套资源的 SO 问题:

What are best practices for REST nested resources

ID /items/1/types 的意思类似于 "display all types belonging to the item with id 1"。而 /items/types 并没有真正意义,因为资源类型不能属于所有项目资源。

但是,您可以使用 @list_route 装饰器将其作为 ViewSet 的自定义操作来实现,例如

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

虽然这可能不是 RESTful 方式。

Docs on custom ViewSet actions