python Django Rest在URL中需要参数

3npbholx  于 2023-03-16  发布在  Python
关注(0)|答案(2)|浏览(104)

我使用的是django rest框架,下面是我的代码:

网址.py:

urlpatterns = [
    url(r'^users/show', UserShow.as_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

我想从url中获取值,如下所示:/users/show?user_id=1/users/show?username=mike

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

用我的代码,如果我发送的请求与错误的参数名称/users/show?user111name=mike或简单的/users/show视图当然回应我与queryset = User.objects.all(),并列出所有的用户。我不需要。我需要如果所需的参数是None响应与404。
我可以通过基于函数的视图获得所需结果:

@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)

但是我如何使用泛型基于类的视图呢?

sczxawaw

sczxawaw1#

class UserIdRetrieve(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
class UserUsernameRetrieve(UserIdRetrieve):
     lookup_field = 'username'

以及URL中:

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

如果你url结构是必须的,对上面的做些小改动:

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 ValidationError('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

以及URL中:

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

cwxwcias2#

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)

相关问题