I have the following model:
class Vacancy(models.Model):
lat = models.FloatField(\'Latitude\', blank=True)
lng = models.FloatField(\'Longitude\', bla
On Django 3.0 there will be a GeometryDistance function, which works the same way as Distance
, but uses the <-> operator instead, which uses spatial indexes on ORDER BY
queries, eliminating the need for a dwithin
filter:
from django.contrib.gis.db.models.functions import GeometryDistance
from django.contrib.gis.geos import Point
ref_location = Point(140.0, 40.0, srid=4326)
Vacancy.objects.annotate(
distance=GeometryDistance('location', ref_location)
).order_by('distance')
If you want to use it before Django 3.0 is released, you could use something like this:
from django.contrib.gis.db.models.functions import GeoFunc
from django.db.models import FloatField
from django.db.models.expressions import Func
class GeometryDistance(GeoFunc):
output_field = FloatField()
arity = 2
function = ''
arg_joiner = ' <-> '
geom_param_pos = (0, 1)
def as_sql(self, *args, **kwargs):
return Func.as_sql(self, *args, **kwargs)