【问题标题】:Using template for rendering Point (coordinates) in django haystack在 django haystack 中使用模板渲染点(坐标)
【发布时间】:2015-08-06 19:02:39
【问题描述】:

我想做的是通过 django-haystack 实现地理空间搜索。在官方guide 中,他们建议将普通浮点坐标转换为django.contrib.gis.geos.Point 对象。但是,在本指南中,他们没有提到如何在模板中呈现 Points。当我尝试这样做时,我遇到了下一个异常:

 raise SpatialError("Point '%s' doesn't appear to be a GEOS geometry." % geom)
haystack.exceptions.SpatialError: Point 'POINT (49.8448879999999974 40.3779240000000001)' doesn't appear to be a GEOS geometry.

模型类是这样的:

class Shop(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()

    def get_location(self):
        return Point(self.latitude, self.longitude)

索引如下所示:

class ShopIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    location = indexes.LocationField(model_attr='get_location', use_template=True)

    def get_model(self):
         return Shop

    def index_queryset(self, using=None):
         return self.get_model().objects.all()

渲染位置的模板如下:

{{ object.get_location }}

有没有其他方法可以在模板中声明坐标? (所以它们可以被 haystack 用于地理空间搜索)?或者对于异常描述的问题有什么解决方法?

更新

唯一应该使用位置的地方是下一个搜索查询:

# The point, around which we do want to search
point = Point(lon, lat)
# radius of geospatial search
distance = D(km=rad)

SearchQuerySet().models(models.Location).dwithin('location', point, distance)

【问题讨论】:

  • 不确定这里是否重要,但 Point 构造函数将经度作为第一个参数,即Point(self.longitude, self.latitude),因此您可能会因此而出错。
  • 另一种尝试可能是将几何图形返回为 WKT。不确定模板引擎如何将点转换为 wkt。所以在你的函数中,你能返回Point(self.longitude, self.latitude).wkt吗?我怀疑这是问题所在,但对于您想要的内容会更明确。
  • 另外,您能否提供更多您的模板?你在哪里使用位置,是调用另一个函数吗?因此,如果您可以将上面的模板示例前后扩展几行,可能更容易理解问题所在。
  • 在 haystack 文档的示例中,LocationField 不使用模板。您是否尝试为该字段保留模板部分?
  • 距离查找可能不支持模板部分。在这种情况下,您需要采用您所描述的自定义方法。

标签: django django-haystack geodjango


【解决方案1】:

您必须将 Point 对象转换为 Geometry 对象。然后修改search_indexes.py中写的get_model方法

from django.contrib.gis import geos
def get_location(self):<br>
return geos.fromstr("POINT(%s %s)" %(self.longitude, self.latitude))

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2022-07-22
    • 2012-02-29
    • 2019-09-26
    • 2011-09-28
    • 2020-12-18
    • 2018-05-20
    • 2018-11-05
    • 2020-08-10
    相关资源
    最近更新 更多