【问题标题】:GeoDjango distance of related model相关模型的GeoDjango距离
【发布时间】:2015-07-16 21:59:19
【问题描述】:

我正在尝试返回一个与相关模型有距离的查询集。

models.py(简化版)

class Store(models.Model):
    geopoint = models.PointField(srid=4326)

    objects = models.GeoManager()


class HashTag(models.Model):
    tag = models.CharField(max_length=100)


class Label(models.Model):
    hashtags = models.ManyToManyField(HashTag)
    store = models.ForeignKey(Store)

我需要返回的是具有特定标签/标签的标签对象,这些标签按距给定点的距离排序。

标签可以通过以下方式找到:

Label.objects.filter(hashtags__in=tags)

Store 对象上的距离可用:

Store.objects.filter(label__hashtags__in=tags)
             .distance(location).order_by('distance')

我想做的是对Label 表执行查询以返回所有内容,但我怀疑这是不可能的。

在查询集上尝试distance 方法会导致:

TypeError: ST_Distance output only available on GeometryFields.

没有做最有效的次优事情是有意义的。我能想到的唯一解决方案是执行两个查询并将结果合并到一个集合中。

【问题讨论】:

  • 在它发布一年后偶然发现!你正在做距离(位置),但你的领域似乎是地理点。那么您的查询不应该是 distance('geopoint') 吗?
  • 嘿,@RobinElvin,我想知道,你觉得我(很晚)的回答有帮助吗?
  • @JohnMoutafis 抱歉,这个项目早已不复存在,所以我无法针对原始问题进行测试。如果其他人认为它有效,我会接受你的回答。

标签: python django postgis geodjango


【解决方案1】:

绝对可以实现你的查询:

  • 使用annotate() 在每个Label 对象上附加一个距离值。
  • 使用Distance()函数计算每个店铺的geopointlocation点的距离

查询应如下所示:

from django.contrib.gis.db.models.functions import Distance

Label.objects.filter(hashtags__in=tags)
             .annotate(distance=Distance('store__geopoint', location))
             .order_by('distance')

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2015-02-12
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多