1

我将我的 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']})
4

1 回答 1

1

所以这是最小可重现的例子:

# 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/'

因此,确实您的错误只是传递了路由器基本名称而不是最终端点来反转,并且由于嵌套,我们被学生详细信息不反转(我仍然没有得到)抛出。

于 2020-07-25T18:10:13.977 回答