【问题标题】:I can not sort by city distance in GeoDjango (PostGis)我无法在 GeoDjango (PostGis) 中按城市距离排序
【发布时间】:2019-03-14 00:16:26
【问题描述】:

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

【问题讨论】:

    标签: python django postgis geodjango


    【解决方案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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 2014-03-09
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多