如何设置细节和在Django rest_framework的ViewSet中的lookup_field?

时间:2018-06-14 06:11:49

标签: python django django-rest-framework router

我想在一个类中使用两个函数。

一个函数是detail = False,另一个函数是detail = True。

所以我想使用这样的两个url模式,

/userinfo/users
/userinfo/search/(search_key)

但是我得到NoReverseMatch错误,如下所示,我该如何解决?

错误

NoReverseMatch at /userinfo/users/
Reverse for 'userinfo-search' with no arguments not found. 1 pattern(s) tried: ['userinfo/(?P<search_key>[^/.]+)/search/$']

forms.py

class ModelInfoForm(forms.Form):
    search_key = forms.CharField(
        required=True,
        widget=forms.TextInput(
            attrs={
                'placeholder': 'input keyword',
                'class': 'form-control w-50 mr-sm-2',
                'type': 'search',
                'aria-label': 'search'
            }
        )
    )

urls.py

router = routers.SimpleRouter()
router.register(r'userinfo', UserinfoViewSet, 'userinfo')

view.py

class UserinfoViewSet(viewsets.ModelViewSet):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'user/userinfo.html'

    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [AllowAny]
    lookup_field = 'search_key'

    @action(methods=['get'], detail=False)
    def users(self, request):
        form = ModelInfoForm(request.GET or None)

        serializer = UserSerializer(self.queryset, many=True)
        return Response({'users':serializer.data, 'form':form})

    @action(methods=['post'], detail=True)
    def search(self, request):
            form = ModelInfoForm(request.POST or None)
            search_key = request.POST['search_key']

            for user in self.queryset:
                if not search_key in user.username:
                    self.queryset = self.queryset.exclude(username=user.username)

            serializer = UserSerializer(self.queryset, many=True)
            return Response({'users':serializer.data, 'form':form})

0 个答案:

没有答案