Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I access request parameters in Django Rest Framework?

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

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?

like image 766
RknRobin Avatar asked Oct 29 '16 23:10

RknRobin


2 Answers

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.

like image 193
JClarke Avatar answered Sep 19 '22 17:09

JClarke


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
like image 37
Blairg23 Avatar answered Sep 16 '22 17:09

Blairg23