0

我有这个添加了自定义操作的视图集

@permission_classes([IsStaffUser])
class MacroViewSet(viewsets.ModelViewSet):
    queryset = Macro.objects.all()
    serializer_class = MacroSerializer
    http_method_names = ['get', 'post', 'patch', 'head', 'delete']

    @action(methods=['post'], detail=True, url_name='add-student')
    def add_student(self, request, pk=None):
        pass

在urls.py中注册为

# application namespace
app_name = 'appname'

router = routers.DefaultRouter()
router.register(r'users', UserViewSet, basename='user')
router.register(r'students', StudentViewSet)
router.register(r'macro', MacroViewSet, basename='macro')

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

现在,我正在尝试测试我的自定义操作。当然我需要它的网址。按照drf guide,我知道reverse_action方法的存在。在我的测试用例中,我使用该方法如下

self.url = MacroViewSet().reverse_action('add-student', args=['1'])

不幸的是,我不断收到此错误

>       self.url = MacroViewSet().reverse_action('add-student', args=['1'])
E       AttributeError: 'MacroViewSet' object has no attribute 'basename'
4

0 回答 0