我指的是下面列出的問題中的答案,因爲我試圖運行一個查詢來獲取距我的django應用程序中給定點最近的對象。我的Django版本是1.9.2。對象沒有屬性「距離」 - GeoDjango
How to return a record with the lowest distance from a point using geodjango?
在我看來,我傳遞一個郵政編碼,並使用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
的章模型有一個名爲位置這是一個點場場。
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'
Edit--
當嘗試使用替代方法中的問題,讓以上的距離我得到一個不同的錯誤讓我覺得我的模型有問題。
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'
我只是想這和它仍然沒有工作。在嘗試循環並獲得每個實例的距離後,我只是在該問題中添加了一些額外的上下文。 –
@BrandonMitchell這兩個條件的問題都是一樣的。 **第**章模型沒有名爲** distance **的字段/屬性。 –
@BrandonMitchell請在問題中添加模型**章**的代碼。這將有助於解決問題。 –