如何更改路由器 URL 前缀以在 Django Rest Framework (DRF) 中传递双重查找字段

How to change router URL prefix to pass double lookup field in Django Rest Framework (DRF)

我想为特殊博客 post 的评论设置 URL。所以我需要那个博客的ID,但我不知道如何更改前缀。

url.py

from django.urls import path, include
from rest_framework.routers import SimpleRouter

from .views import BlogViewSet, CommentViewSet

router = SimpleRouter()
router.register('blog', BlogViewSet, basename='blog')
router.register('blog/<int:id>/comments', CommentViewSet, basename='comments')
urlpatterns = [
   path('', include(router.urls)),

]

我们可以使用 drf-nested-routers 包来做到这一点。 drf-nested-router

from django.urls import path, include
from rest_framework.routers import SimpleRouter
from rest_framework_nested import routers

from .views import BlogViewSet, CommentViewSet


router = SimpleRouter()
router.register('blog', BlogViewSet, basename='blog')
domains_router = routers.NestedSimpleRouter(router, r'blog', lookup='blog')
domains_router.register(r'comments', CommentViewSet, basename='comments')
urlpatterns = [
    path('', include(router.urls)),
    path('', include(domains_router.urls)),

]