Where can I access request parameters in Django Rest Framework?

大兔子大兔子 提交于 2021-02-18 22:37:07

问题


I'm using Django Rest Framework and python-requests and passing several variables through the URL as shown below.

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

So I'm passing the variables make, model, and plastic. The recommended method to access these parameters is shown below.

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

However, I have no idea where to place that line of code. I've completed the tutorial for Django Rest Framework and have my views set up to roughly match the tutorial.

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?")
    '''

Where would I place the one line of code to access these request parameters?


回答1:


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

What is the statement doing ?

If 'make' is in the query params of the request then overwrite the BoxViewSet queryset property with a new queryset based on 'make' and return it. otherwise return the default queryset that excludes any objects that isn't verified.




回答2:


Based on Django Rest Framework's Filtering Documentation, there are two ways to access parameters from a request.

1. URL Params

If you are using URL params (such as mywebapp.com/api/<user_slug>/resource/), you can access the arguments like this: self.kwargs['param_name'] where param_name is the name of the parameter you're trying to get the value for. So for the example above, you'd have user_slug = self.kwargs['user_slug']

Example from the documentation

If your URL structure looks like this:

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

...and want to filter on that username. You can override the get_queryset() and your view will look like this:

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. Query Params

If you are using query parameters such as mywebapp.com/api/resource?user_slug=plain-jane, you can use self.request to access request as you can in plain vanilla Django REST methods. This gives you access to things like self.request.query_params. For the example above, you would say user_slug = self.request.query_params['user_slug']. You can also access the current user like user = self.request.user.

Example from the documentation

Let's say you want to support a request structure like this:

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

...and want to filter on that username. Do this to override the queryset:

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



回答3:


adding a little to what they have already contributed, for the POST methods in modelviewset when an object is sent, it is necessary to use request.data['myvariable']

example:

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']



回答4:


Django 2

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


来源:https://stackoverflow.com/questions/40324756/where-can-i-access-request-parameters-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!