I have following ViewSet:
class BookViewSet(DefaultsMixin, viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
@detail_route()
def chapter(self, request,pk=None):
queryset = Chapter.objects.filter(book__pk=pk)
serializer = ChpaterSerializer(queryset,
context={'request':request},
many=True)
return Response(serializer.data)
So the url "/book/{id}/chapter" is valid. But I don't know how I can config the ViewSet to have a url like "/book/{id}/chapter/{id}". Maybe answer is using lookup_field or lookup_url_kwarg but I can not find usage them in the detail_route case.
for this to work in my viewsets i did:
from above you can retrieve id from url via pk variable.
Change the above password method to
you can do this adding
url_path
in thedetail_route
like:Note that the name of the url in the default router defaults to the
url_path
argument if it is provided. So the view name would inlcude the query parameter string. By specifying theurl_name
argument, you can simplify that. I would recommend to use the method name there, which is the default ifurl_path
is not specified. With that, you can reverse the url with