Django Rest Framework, passing parameters with GET request, classed based views

GRS picture GRS · Jan 17, 2018 · Viewed 45k times · Source

I would like a user to send a GET request to my Django REST API:

127.0.0.1:8000/model/?radius=5&longitude=50&latitude=55.1214

with his longitude/latitude and radius, passed in parameters, and get the queryset using GeoDjango.

For example, currently I have:

class ModelViewSet(viewsets.ModelViewSet):
    queryset = Model.objects.all()

And what I ideally want is:

class ModelViewSet(viewsets.ModelViewSet):
     radius = request.data['radius']
     location = Point(request.data['longitude'],request.data['latitude']
     # filter results by distance using geodjango
     queryset = Model.objects.filer(location__distance_lte=(location, D(m=distance))).distance(location).order_by('distance')

Now a couple of immediate errors:

1) request is not defined - should I use api_view, i.e. the function based view for this?

2) DRF page says that request.data is for POST, PUT and PATCH methods only. How can send parameters with GET?

Answer

Ozgur Akcali picture Ozgur Akcali · Jan 17, 2018

You can override get_queryset method for that purpose. As for query string parameters, you are right, request.data holds POST data, you can get query string params through request.query_params

def get_queryset(self):
    longitude = self.request.query_params.get('longitude')
    latitude= self.request.query_params.get('latitude')
    radius = self.request.query_params.get('radius')

    location = Point(longitude, latitude)

    queryset = Model.objects.filter(location__distance_lte=(location, D(m=distance))).distance(location).order_by('distance')

    return queryset