Django sort by distance

前端 未结 7 1005
旧时难觅i
旧时难觅i 2020-11-28 04:34

I have the following model:

class Vacancy(models.Model):
    lat = models.FloatField(\'Latitude\', blank=True)
    lng = models.FloatField(\'Longitude\', bla         


        
相关标签:
7条回答
  • 2020-11-28 05:33

    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)
    
    0 讨论(0)
提交回复
热议问题