Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 787
GRS Avatar asked Jan 17 '18 10:01

GRS


People also ask

How do you use class based views in Django REST Framework?

To make use of generic class-based views, the view classes should import from rest_framework. generics. ListAPIView: It provides a get method handler and is used for read-only endpoints to represent a collection of model instances. ListAPIView extends GenericAPIView and ListModelMixin.

What is difference between APIView and Viewset?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

What is DjangoFilterBackend?

The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters. rest_framework. FilterSet) class for the given fields. We can also create our own FilterSet class with customized settings.


1 Answers

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 
like image 106
Ozgur Akcali Avatar answered Oct 01 '22 22:10

Ozgur Akcali