Django Rest需要URL中的参数

时间:2021-07-13 19:37:14

I'm using django rest framework. Here is my code:

我正在使用django rest框架。这是我的代码:

urls.py:

urls.py:

urlpatterns = [
    url(r'^users/show', UserShow.as_view()),
]

view.py:

view.py:

class UserShow(ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_queryset(self):
        queryset = User.objects.all()
        username = self.request.query_params.get('username', None)
        user_id = self.request.query_params.get('user_id', None)
        if username is not None:
            queryset = queryset.filter(username=username)
        if user_id is not None:
            queryset = queryset.filter(pk=user_id)
        return queryset

I want to get values from url like this: /users/show?user_id=1 or /users/show?username=mike.

我想从url获取这样的值:/ users / show?user_id = 1或/ users / show?username = mike。

Either an user_id or username must be required parameter. How can I control it in class based views?

user_id或username必须是必需参数。如何在基于类的视图中控制它?

With my code if I'm sending the request with wrong parameter name /users/show?user111name=mike or simple /users/show the view of course response me with queryset = User.objects.all() and lists all the users. I don't need that. I need if required parameters are None response with 404.

使用我的代码,如果我发送带有错误参数名称/ users / show的请求?user111name = mike或simple / users / show视图当然用queryset = User.objects.all()回复我并列出所有用户。我不需要那个。如果需要的参数是404的无响应,我需要。

I can get needed result with function based view:

我可以通过基于函数的视图得到所需的结果:

@api_view(['GET'])
def users(request):
    if request.method == 'GET':
        queryset = User.objects.all()
        username = request.GET.get('username', None)
        user_id = request.GET.get('user_id', None)

        if username is not None:
            queryset = queryset.filter(username=username)
        elif user_id is not None:
            queryset = queryset.filter(pk=user_id)
        else:
            return Response({"status": "required field not found."},
                            status=status.HTTP_404_NOT_FOUND)

        if not queryset.exists():
            return Response({"status": "not found."},
                            status=status.HTTP_404_NOT_FOUND)

        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

But how can I do it with generic class based views?

但是如何使用基于通用类的视图呢?

2 个解决方案

#1


0  

class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserUsernameRetrieve(UserIdRetrieve):
     lookup_field = 'username'

and in urls:

并在网址中:

urlpatterns = [
    url(r'^users/(?P<pk>\d+)/', UserIdRetrieve.as_view()), 
    url(r'^users/by-username/(?P<username>\w+)/', UserUsernameRetrieve.as_view())
]

if your url structure is a must, small change to above:

如果您的网址结构是必须的,小的更改为上面:

class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())

        if 'username' in self.request.query_params:
            filter_kwargs = {'username': self.request.query_params['username']}
        elif 'user_id' in self.request.query_params:
             filter_kwargs = {'id': self.request.query_params['user_id']}
        else:
            raise Http404('Missing required parameters')

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

and in urls:

并在网址中:

urlpatterns = [
    url(r'^users/show', UserRetrieve.as_view())
]

#2


-1  

class UserShow(ListAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def filter_queryset(self, queryset):
        username = self.request.query_params.get('username', None)
        user_id = self.request.query_params.get('user_id', None)

        if username is not None:
            queryset = queryset.filter(username=username)
        if user_id is not None:
            queryset = queryset.filter(pk=user_id)
        return queryset

    def list(self,request,*args,**kwargs):
        username = self.request.query_params.get('username', None)
        user_id = self.request.query_params.get('user_id', None)
        if not (username or user_id):
            return Response({"status": "Required field not found."},
                                        status=status.HTTP_404_NOT_FOUND)
        return super(UserShow, self).list(request,*args,**kwargs)

#1


0  

class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserUsernameRetrieve(UserIdRetrieve):
     lookup_field = 'username'

and in urls:

并在网址中:

urlpatterns = [
    url(r'^users/(?P<pk>\d+)/', UserIdRetrieve.as_view()), 
    url(r'^users/by-username/(?P<username>\w+)/', UserUsernameRetrieve.as_view())
]

if your url structure is a must, small change to above:

如果您的网址结构是必须的,小的更改为上面:

class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())

        if 'username' in self.request.query_params:
            filter_kwargs = {'username': self.request.query_params['username']}
        elif 'user_id' in self.request.query_params:
             filter_kwargs = {'id': self.request.query_params['user_id']}
        else:
            raise Http404('Missing required parameters')

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

and in urls:

并在网址中:

urlpatterns = [
    url(r'^users/show', UserRetrieve.as_view())
]

#2


-1  

class UserShow(ListAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def filter_queryset(self, queryset):
        username = self.request.query_params.get('username', None)
        user_id = self.request.query_params.get('user_id', None)

        if username is not None:
            queryset = queryset.filter(username=username)
        if user_id is not None:
            queryset = queryset.filter(pk=user_id)
        return queryset

    def list(self,request,*args,**kwargs):
        username = self.request.query_params.get('username', None)
        user_id = self.request.query_params.get('user_id', None)
        if not (username or user_id):
            return Response({"status": "Required field not found."},
                                        status=status.HTTP_404_NOT_FOUND)
        return super(UserShow, self).list(request,*args,**kwargs)