问题描述
我正在尝试使用Django和Postgresql实现基于纬度和经度的邻近搜索。这是我所拥有的抽象版本。
I am trying to implement a proximity search based on latitude and longitude using Django and Postgresql. Here's the abstract version of the Model I have.
class Item(models.Model):
"""docstring for Item"""
uuid = UUIDField(primary_key=True, auto=True)
name = models.CharField(_("name"), max_length=200)
address = models.CharField(_('street address'), max_length=255, blank=True, null=True)
location = models.CharField(_('location'), max_length=40, blank=True, null=True)
@property
def geo_distance(self, location=None):
if location is not None:
cursor = connection.cursor()
cursor.execute("SELECT geo_distance(CAST('%s')) AS POINT, CAST('%s') AS POINT)" %
self.location, location)
return round(float(cursor.fetchone() * 1.621371192237), 2)
我想要能够做这样的事情在views.py:
I want to be able to do something like this in views.py:
items = Item.objects.filter(name__istartwith="Anything")
results = []
for item in items:
results.append({
'name': item.name,
'distance': item.geo_distance("(11.23123, -12.123213)")
})
我意识到这不是最好的方法。任何建议欢迎。
I realize that this is not the best approach. Any suggestions welcome.
推荐答案
如果您根据纬度和经度进行搜索,我会推荐您。要计算X点的两点或周边区域之间的距离,您可以使用。最好使用编写距离计算。据我所知,django不支持创建程序,我在计算距离方面做了一些基准,我发现程序要更快,而不是在django端计算。祝你好运。
If you a search based on latitude and longitude I would recommend you GeoDjango. To calculate distance between a two point or surrounding area from point X you can use Haversine formula. It better to write the distance calculation by using procedure. To my knowledge django doesn't support creating procedures, I made some benchmark in terms of calculating distance, i found procedures to be faster rather than calculating on the django end. Good Luck.
这篇关于Django模型属性地理距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!