Viewsets in Django Rest Framework keep my code very clean: I can define a model and then a viewset to go along with it.
However, how do I best deal with models which are hierarchically under another one? For example: I have a Project which has many Files and want this API:
GET /api/files: get all files across all projectsGET /api/files/:id: detail a particular fileGET /api/projects/:id/files: list all files in a project
The following code almost works, except that the URL for 3. comes out as api/files/projects/:id:
class FileViewSet(
mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet
):
queryset = File.objects.all()
serializer_class = FileSerializer
@action(methods=["get"], url_path="projects/(?P<project_id>[^/.]+)", detail=False)
def list_for_project(self, request, project_id):
project = Project.objects.get(id=project_id)
# ... list only Files for this Project
I have looked in to a few solutions such as writing custom routers, using more than one viewset or view, or custom packages; but I'm surprised that it isn't easy to do with DRF out-of-the-box within one Viewset. Am I missing a trick? What do people usually do in this scenario?