使用drf-nested-routers
,我们实现了许多嵌套的路由,这些路由的深度为两个级别。
就像在文档中的示例一样:
/clients/
/clients/{pk}/
/clients/{client_pk}/maildrops/
/clients/{client_pk}/maildrops/{pk}/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
字符串
但是,我不喜欢第四行的不一致。我怎么才能让lookup_url_kwarg
也成为maildrop_pk
呢?
/clients/{client_pk}/maildrops/{maildrop_pk}/
型urls.py
看起来是这样的:
# urls.py
router = DefaultRouter()
router.register(r'clients', ClientViewSet, basename='clients')
## generates:
# /clients/
# /clients/{pk}/
client_router = routers.NestedSimpleRouter(router, r'clients', lookup='client')
client_router.register(r'maildrops', MailDropViewSet, basename='maildrops')
## generates:
# /clients/{client_pk}/maildrops/
# /clients/{client_pk}/maildrops/{pk}/
maildrops_router = routers.NestedSimpleRouter(client_router, r'maildrops', lookup='maildrop')
maildrops_router.register(r'recipients', MailRecipientViewSet, basename='recipients')
## generates:
# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
# /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
urlpatterns = [
path(r'', include(router.urls)),
path(r'', include(client_router.urls)),
path(r'', include(maildrops_router.urls)),
]
型
如果我将MailDropViewSet
中的lookup_url_kwarg
设置为maildrop_pk
:
class MailDropViewSet(viewsets.ViewSet):
serializer_class = MailDropSerializer
lookup_url_kwarg = "maildrop_pk"
型
那么路由看起来像这样:
/clients/{client_pk}/maildrops/{maildrop_pk}/
/clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/
/clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/{pk}/
型
我希望在路由中对URL查找kwargs进行一致的命名,例如:
/clients/{client_pk}/maildrops/{maildrop_pk}/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/
/clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/
型
但我看不出这是怎么配置的
1条答案
按热度按时间ctzwtxfj1#
虽然不理想,但一个想法可能是制作我们自己的
NestedSimpleRouter
,使用:字符串
并将其混合成
NestedSimpleRouter
:型
因此,我们可以将其用作:
型
所以
ViewSet
s的lookup_url_kwarg
s决定了参数的名称,这将定义URL模式。当然,结果是
lookup_url_kwarg
应该在所有ViewSet
上定义,对于它们生成的所有路径,永远不会有两个同名的路径参数。