我有以下模型:
class Vacancy(models.Model): lat = models.FloatField('Latitude', blank=True) lng = models.FloatField('Longitude', blank=True)
我应如何查询以距离排序(距离为无穷大)?
如果需要,可以在PosgreSQL,GeoDjango上工作。
首先,最好使一个点字段而不是使lat和lnt分开:
from django.contrib.gis.db import models location = models.PointField(null=False, blank=False, srid=4326, verbose_name="Location")
然后,你可以像这样过滤它:
from django.contrib.gis.geos import * from django.contrib.gis.measure import D distance = 2000 ref_location = Point(1.232433, 1.2323232) res = yourmodel.objects.filter(location__distance_lte=(ref_location, D(m=distance))).distance(ref_location).order_by('distance')
将.distance(ref_location)在Django> = 1.9,你应该用注解来替代被删除。
.distance(ref_location)
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')