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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With