我有以下模型:
class Vacancy(models.Model):
lat = models.FloatField('Latitude', blank=True)
lng = models.FloatField('Longitude', blank=True)
我应该如何进行查询以按距离排序(距离无穷大)?
如果需要的话,可以使用 PostgreSQL、GeoDjango。
the .distance(ref_location)
在 django >=1.9 中被删除,您应该使用注释。
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.measure import D
from django.contrib.gis.geos import Point
ref_location = Point(1.232433, 1.2323232, srid=4326)
yourmodel.objects.filter(location__distance_lte=(ref_location, D(m=2000)))
.annotate(distance=Distance("location", ref_location))
.order_by("distance")
您还应该缩小搜索范围dwithin
使用空间索引的运算符,距离不使用索引,这会减慢查询速度:
yourmodel.objects.filter(location__dwithin=(ref_location, 0.02))
.filter(location__distance_lte=(ref_location, D(m=2000)))
.annotate(distance=Distance('location', ref_location))
.order_by('distance')
see 这个帖子的解释location__dwithin=(ref_location, 0.02)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)