gpt4 book ai didi

python - 我无法在 GeoDjango (PostGis) 中按城市距离排序

转载 作者:行者123 更新时间:2023-12-01 08:12:33 24 4
gpt4 key购买 nike

距离方法在 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)

查看.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”对象没有属性“距离”

虽然在这个版本中可以使用,但不按距离排序

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)

最佳答案

在 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')

关于python - 我无法在 GeoDjango (PostGis) 中按城市距离排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com