Last active
November 28, 2019 09:19
-
-
Save marteinn/e66aa28e8964efd7937b to your computer and use it in GitHub Desktop.
Sorting by distance filter for django-restframework-gis. MIT license.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
This is an extension to django-restframework-gis that extends on | |
DistanceToPointFilter and adds sorting by distance. | |
It is also possible to add a extra distance field to the returned queryset by | |
adding the flag distance_filter_add_distance = True to the DRF View. | |
""" | |
from rest_framework_gis.filters import DistanceToPointFilter | |
class OrderedDistanceToPointFilter(DistanceToPointFilter): | |
def filter_queryset(self, request, queryset, view): | |
""" | |
Add sorting by distance, in addition to DinstanceToPointerFilter filter | |
""" | |
if not request.query_params.get(self.point_param, None): | |
return queryset | |
point = self.get_filter_point(request) | |
queryset = super(OrderedDistanceToPointFilter, self)\ | |
.filter_queryset(request, queryset, view) | |
queryset = queryset.distance(point) | |
queryset = queryset.order_by('%s' % 'distance') | |
add_distance = getattr(view, 'distance_filter_add_distance', False) | |
if add_distance: | |
queryset = self.apply_distance_field(request, queryset, view) | |
return queryset | |
def apply_distance_field(self, request, queryset, view): | |
""" | |
Adds distance info (in meters) to queryset | |
""" | |
for item in queryset: | |
item.distance = item.distance.m | |
return queryset |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment