Add coordinate filter on the backend

- filters plants based on ecological region and soil order
This commit is contained in:
Dana Lambert 2021-10-19 16:06:21 +13:00
parent aa3f9dc7f0
commit 12ebe31cf5
2 changed files with 39 additions and 0 deletions

View file

@ -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

View file

@ -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