RknRobin RknRobin - 1 month ago 11
Python Question

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"

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?

Answer

I haven't tested it. But from memory I'll assume that's it.

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