Django模型属性地理距离 [英] Django model property geo distance

查看:100
本文介绍了Django模型属性地理距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.

推荐答案

如果您根据纬度和经度进行搜索,我会推荐您 GeoDjango 。要计算X点的两点或周边区域之间的距离,您可以使用 Haversine公式。最好使用程序编写距离计算。据我所知,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模型属性地理距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆