我在哪里可以访问Django Rest Framework中的请求参数?

时间:2016-10-29 23:42:37

标签: python django django-rest-framework

我正在使用Django Rest Framework和python请求,并通过URL传递几个变量,如下所示。

“GET / api / boxobjects /?format = json& make = Prusa& model = i3& plastic = PLA HTTP / 1.1”

所以我传递变量make,model和plastic。访问这些参数的推荐方法如下所示。

makedata = request.GET.get('make', '')

但是,我不知道在哪里放置那行代码。我已经完成了Django Rest Framework的教程,并将我的视图设置为与教程大致相符。

views.py

@api_view(['GET'])
@login_required
def api_root(request, format=None):
    return Response({
        'Users': reverse('api:user-list', request=request, format=format),
        'Objects': reverse('api:object-list', request=request, format=format),
        'Files': reverse('api:file-list', request=request, format=format),
        'Config Files': reverse('api:config-list', request=request, format=format),
        'Box-objects': reverse('api:box-object-list', request=request, format=format),

    })

class BoxViewSet(viewsets.ModelViewSet):

    queryset = Uploadobject.objects.all().exclude(verified=False)
    serializer_class = BoxSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                            IsBox)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    #Maybe get function here? Not displaying
    '''
    def get(self, request):
        print ("request set here?")
    '''

我将在哪里放置一行代码来访问这些请求参数?

4 个答案:

答案 0 :(得分:5)

class BoxViewSet(viewsets.ModelViewSet):
    queryset = Uploadobject.objects.all().exclude(verified=False)
    serializer_class = BoxSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                            IsBox)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


    def get_queryset(self):
        req = self.request
        print(req)
        make = req.query_params.get('make')
        if make:
            self.queryset = uploadobject.objects.filter(make=make)
            return self.queryset
        else:
            return self.queryset

声明在做什么?

如果'make'位于请求的查询参数中,则使用基于BoxViewSet的新查询集覆盖'make' queryset属性并将其返回。否则返回排除任何未验证对象的默认查询集。

答案 1 :(得分:1)

基于Django Rest Framework的Filtering Documentation,有两种方法可以从请求中访问参数。

1。网址参数

如果您使用的是URL参数(例如mywebapp.com/api/<user_slug>/resource/),则可以访问以下参数:self.kwargs['param_name']其中param_name是您尝试获取的参数的名称的价值。因此,对于上面的示例,您将拥有user_slug = self.kwargs['user_slug']

文档中的示例

如果您的网址结构如下所示:

url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),

...并希望过滤该用户名。您可以覆盖get_queryset(),您的视图将如下所示:

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases for
        the user as determined by the username portion of the URL.
        """
        username = self.kwargs['username']
        return Purchase.objects.filter(purchaser__username=username)

2。查询参数

如果您使用mywebapp.com/api/resource?user_slug=plain-jane等查询参数,则可以使用self.request访问request,就像普通的Django REST方法一样。这样您就可以访问self.request.query_params之类的内容。对于上面的示例,您会说user_slug = self.request.query_params['user_slug']。您还可以访问当前用户,例如user = self.request.user

文档中的示例

假设您要支持这样的请求结构:

http://example.com/api/purchases?username=denvercoder9

...并希望过滤该用户名。这样做是为了覆盖查询集:

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
            queryset = queryset.filter(purchaser__username=username)
        return queryset

答案 2 :(得分:0)

对于已发送的内容进行一些补充,对于发送对象时在modelviewset中的POST方法,必须使用request.data['myvariable']

示例:

class BoxViewSet(viewsets.ModelViewSet):

    queryset = Uploadobject.objects.all().exclude(verified=False)
    serializer_class = BoxSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                        IsBox)

    def create(self, request):
       ...
       make = request.data['make']

答案 3 :(得分:0)

Django 2

使用 request.parser_context

 def perform_create(self, serializer):
        post_id = self.request.parser_context['kwargs'].get('post_id')
        post = Post.objects.get(id=post_id)
        serializer.save(post=post)