Django - 使用 drf-nested-routers 反向嵌套 url

Django - reverse nested url with drf-nested-routers

我将 api url 配置为

localhost:port/app_name/students/{student_id}/macro/{macro_id}/lto

使用 drf-nested-routers 扩展。基本上,每个学生都分配了一些宏观类别,而这些类别又有一些长期目标 (LTO)。我已经使用 curlPostman 对其进行了测试,一切似乎都正常。 现在我需要为我的 LTO 模型编写一个更精确的测试用例。 这是我的 urls.py

from django.urls import path, re_path
from django.conf.urls import include
from rest_framework import routers
from app_name.views.views import UserViewSet, StudentViewSet, MacroViewSet, LTOViewSet, MacroAssignmentViewSet
from rest_framework_nested import routers as nested_routers

# application namespace
app_name = 'app_name'

router = routers.DefaultRouter()
router.register(r'users', UserViewSet, basename='user')
router.register(r'macro', MacroViewSet, basename='macro')
router.register(r'macro-assignments', MacroAssignmentViewSet, basename='macro-assignment')

student_router = routers.DefaultRouter()
student_router.register(r'students', StudentViewSet, basename='student')
lto_router = nested_routers.NestedSimpleRouter(student_router, r'students', lookup='student')
lto_router.register(r'macro/(?P<macro_pk>.+)/lto', LTOViewSet, basename='lto')


urlpatterns = [
    re_path('^', include(router.urls)),
    re_path('^', include(student_router.urls)),
    re_path('^', include(lto_router.urls)),
]

问题是我无法正确使用 reverse() 方法来获取我的 LTOViewSet 的 url 来测试它。

self.url = reverse('app_name:student-detail:lto', {getattr(self.student, 'id'), getattr(self.macro, 'id')})

这会产生以下错误

django.urls.exceptions.NoReverseMatch: 'student-detail' is not a registered namespace inside 'app_name'

在其他测试用例中,我使用非常相似的句子并且效果很好

self.list_url = reverse('app_name:student-list')

reverse('app_name:student-detail', {post_response.data['id']})

下面是可重现性最低的示例:

# main/viewsets.py
from rest_framework.viewsets import ModelViewSet
from django.contrib.auth.models import User, Group


class StudentViewSet(ModelViewSet):
    model = User


class LTOViewSet(ModelViewSet):
    model = Group
# main/urls.py
from django.urls import re_path, include
from rest_framework import routers

from rest_framework_nested import routers as nested_routers
from .viewsets import StudentViewSet, LTOViewSet

# application namespace
app_name = "main"

student_router = routers.DefaultRouter()
student_router.register(r"students", StudentViewSet, basename="student")
lto_router = nested_routers.NestedSimpleRouter(
    student_router, r"students", lookup="student"
)
lto_router.register(r"macro/(?P<macro_pk>.+)/lto", LTOViewSet, basename="lto")

urlpatterns = [
    re_path("^", include(student_router.urls)),
    re_path("^", include(lto_router.urls)),
]
reverse('main:lto-detail', args=(1,1,1))
Out[5]: '/api/students/1/macro/1/lto/1/'

所以你的错误确实是传递了路由器基名而不是要反转的最终端点,并且由于嵌套,我们被学生细节不反转(我仍然不明白)抛弃了。