我将我的 api url 配置为
localhost:port/app_name/students/{student_id}/macro/{macro_id}/lto
使用drf-nested-routers扩展。基本上,每个学生都分配了一些宏观类别,而这些类别又具有一些长期目标 (LTO)。我已经使用curl和Postman对其进行了测试,一切似乎都有效。现在我需要为我的 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']})