Django rest框架:在detail_route中查询参数 [英] Django rest framework: query parameters in detail_route
问题描述
我有以下ViewSet:
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)
因此url / book / {id} / chapter有效。
但是我不知道如何配置ViewSet以使其具有类似 / book / {id} / chapter / {id}的网址。
也许答案是使用 lookup_field 或 lookup_url_kwarg ,但在detail_route情况下我找不到它们的用法。
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.
推荐答案
您可以在 detail_route
中添加 url_path
,例如:
you can do this adding url_path
in the detail_route
like:
@detail_route(url_name='chapter', url_path='chapter/(?P<chapter_id>[0-9]+)')
def chapter(self, request, pk=None, chapter_id=None):
queryset = Chapter.objects.filter(book__pk=pk)
serializer = ChpaterSerializer(queryset,
context={'request':request},
many=True)
return Response(serializer.data)
请注意,默认路由器中的url名称默认为 url_path
参数(如果提供)。因此,视图名称将包括查询参数字符串。通过指定 url_name
自变量,可以简化此过程。我建议在此处使用方法名称,如果未指定 url_path
,则为默认名称。这样,您可以使用以下反向链接
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 the url_name
argument, you can simplify that. I would recommend to use the method name there, which is the default if url_path
is not specified. With that, you can reverse the url with
reverse('book-chapter', kwargs={'pk': 1, 'chapter_id': 4})
这篇关于Django rest框架:在detail_route中查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!