我指的是下面列出的问题中的答案,因为我正在尝试运行一个查询,该查询获取与我的django应用程序中给定点最接近的对象。我的django版本是1.9.2。
How to return a record with the lowest distance from a point using geodjango?
在我看来,我传递一个Zipcode并使用GeoPy来获取位置和纬度/经度。
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D
from geopy.geocoders import Nominatim
geolocator = Nominatim()
zipcode = self.request.query_params.get('zipcode', None)
distance_m = 20000
if zipcode is not None:
location = geolocator.geocode(zipcode, timeout=None)
origin = Point((location.latitude, location.longitude))
queryset = Chapter.objects.filter(location__distance_lte=(origin, D(m=distance_m))).distance(origin).order_by('distance')[:1][0]
return queryset
章模型有一个名为 location 的字段,这是一个点字段。
from django.contrib.gis.db import models
class Chapter(models.Model):
name = models.CharField(max_length=500)
school = models.ForeignKey(School)
verification = models.CharField(max_length=50)
address1 = models.TextField()
address2 = models.TextField(null=True, blank=True)
city = models.TextField()
state = models.TextField()
zipcode = models.CharField(max_length=5)
location = models.PointField(srid=4326, null=True, blank=True)
is_school = models.BooleanField(default=False)
is_association = models.BooleanField(default=False)
authorized = models.NullBooleanField(default=False)
stripe_account_active = models.NullBooleanField(default=False)
def __unicode__(self):
return self.name
def get_nickname(self):
return self.school.nickname
执行此操作时出现以下错误:
AttributeError: 'QuerySet' object has no attribute 'distance'
修改 -
当我尝试在上面的问题中使用替代方法获得距离时,我得到一个不同的错误,这让我觉得我的模型有问题。
point = Chapter.objects.get(name='Chapter of the Year').location
distance_m = 20000
for chapter in Chapter.objects.distance(point):
print(chapter.name, chapter.distance)
错误:
'Manager' object has no attribute 'distance'
答案 0 :(得分:4)
让这个工作
Chapter.objects.filter(location__distance_lte=(origin, D(m=distance_m))).annotate(distance=Distance('location', origin)).order_by('distance')[:1][0]
答案 1 :(得分:1)
如下所述:
queryset = Chapter.objects.filter(location__distance_lte = (origin, D(m=distance_m))).distance(origin).order_by('distance')[:1][0]
您按距离排序结果,但这不是章节模型中的字段/属性。 我认为你想要的是 location__distance 的顺序,所以实际的过滤查询应该是:
queryset = Chapter.objects.filter(location__distance_lte= (origin, D(m=distance_m))).distance(origin).order_by('location__distance')[:1][0]
此行也完全不正确:
for chapter in Chapter.objects.distance(point):
因为此处距离不是过滤器或获取等方法。 它应该是这样的:
point = Chapter.objects.get(name='Chapter of the Year')
distance_m = 20000
for chapter in Chapter.objects.filter(id = point.id ):
print(chapter.name, chapter.location.distance)