distance方法在GeoDjango(QuerySet)中不起作用
我的模特:
class City(models.Model):
name_english = models.CharField(max_length=500, null=True, blank=True)
site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True, verbose_name="city", db_index=True, related_name="city_relate")
name_city_avito = models.CharField(max_length=500, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Country", db_index=True, related_name="Country_relate")
region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Region", db_index=True, related_name="Region_relate")
point = models.PointField(blank=True, null=True)
view.py
class Landing_head(View):
def get(self, request):
b = Site.objects.get_current()
current_location = City.objects.get(site__id=b.id).point
cities = City.objects.filter(point__distance_lte=(current_location, D(km=200))).distance(current_location).order_by('point_distance')[:1][0]
for z in cities:
print(z)
输出错误'QuerySet'对象没有属性'distance'
尽管它在此版本中有效,但无需按距离排序
class Landing_head(View):
def get(self, request):
b = Site.objects.get_current()
current_location = City.objects.get(site__id=b.id).point
cities = City.objects.filter(point__distance_lte=(current_location, D(km=200)))
for z in cities:
print(z)
答案 0 :(得分:1)
在Django版本> = 1.9中,.distance
不存在。
您需要将距离测量值注释到查询集,然后通过注释字段进行排序:
cities = City.objects.filter(
point__distance_lte=(current_location, D(km=200))
).annotate(
distance=Distance('point', current_location)
).order_by('distance')