From 12ebe31cf5f815596f07708d92b3d2859c92796b Mon Sep 17 00:00:00 2001 From: Dana Lambert Date: Tue, 19 Oct 2021 16:06:21 +1300 Subject: [PATCH] Add coordinate filter on the backend - filters plants based on ecological region and soil order --- backend/right_tree/api/filters.py | 28 ++++++++++++++++++++++++++++ backend/right_tree/api/views.py | 11 +++++++++++ 2 files changed, 39 insertions(+) create mode 100644 backend/right_tree/api/filters.py diff --git a/backend/right_tree/api/filters.py b/backend/right_tree/api/filters.py new file mode 100644 index 0000000..0c9e337 --- /dev/null +++ b/backend/right_tree/api/filters.py @@ -0,0 +1,28 @@ +import json + +from django.contrib.gis.geos import Point +from django.db.models import Q + +from .models import EcologicalRegion, EcologicalDistrictLayer, SoilOrder + + +def coordinate_filter(request, queryset): + coordinates = request.query_params.get('coordinates') + + if coordinates is not None: + coordinates_json = json.loads(coordinates) + pnt = Point(coordinates_json["lng"], + coordinates_json["lat"], srid=4326) + pnt.transform(2193) + + filtered_regions = EcologicalRegion.objects.filter( + ecologicaldistrictlayer__geom__intersects=pnt).values_list('id', flat=True) + filtered_soil_orders = SoilOrder.objects.filter( + soillayer__geom__intersects=pnt).values_list('id', flat=True) + + # Filter by ecological regions and soil orders + return queryset.filter( + Q(ecological_regions__in=filtered_regions) & + Q(soil_order__in=filtered_soil_orders)) + + return queryset diff --git a/backend/right_tree/api/views.py b/backend/right_tree/api/views.py index 6e96597..c1b9949 100644 --- a/backend/right_tree/api/views.py +++ b/backend/right_tree/api/views.py @@ -1,6 +1,7 @@ from rest_framework import viewsets from right_tree.api.models import Plant from right_tree.api.serializers import PlantSerializer +from .filters import coordinate_filter class PlantViewSet(viewsets.ModelViewSet): """ @@ -8,3 +9,13 @@ class PlantViewSet(viewsets.ModelViewSet): """ queryset = Plant.objects.all() serializer_class = PlantSerializer + + def get_queryset(self): + """ Filtering plant query set by query parameters in the URL. + (May want to eventually use django filters to break up the logic...) + """ + queryset = Plant.objects.all() + queryset = coordinate_filter(self.request, queryset) + + return queryset + \ No newline at end of file