直接用django计算geohash,无需创建模型

问题描述 投票:0回答:1

是否可以直接使用这个GeoHash类而不在数据库上创建模型?

例如:

from django.contrib.gis.geos import Point
from django.contrib.gis.db.models.functions import GeoHash
p = Point(x=lon, y=lat, srid=4326)
geohash_str = GeoHash(p).???   # i want the actual geohash string here
django gis geohashing
1个回答
0
投票

GeoHash
 [Django-doc]本身计算任何东西。本质上它只是一些转换为 SQL 表达式的抽象语法树节点。所以算法是在数据库中评估的,而不是由 Django 评估的。

是否可以直接使用这个GeoHash类而不在数据库上创建模型?

是的,或者至少是友善的。我们可以进行

SELECT
查询,并确定其中的 geohash,例如:

您可以使用另一个与它无关的模型来评估它,其中:

from app_name.models import SomeModel
from django.contrib.gis.db.models.functions import GeoHash
from django.contrib.gis.geos import Point
from django.db import connections

db_name = 'default'

connection = connections[db_name]
compiler = conn.ops.compiler('SQLCompiler')(
    SomeModel.objects.none(), connection, db_name
)

with connection.cursor() as cursor:
    sql, params = GeoHash(Point(x=lon, y=lat, srid=4326)).as_sql(
        compiler, connection
    )
    cursor.execute(f'SELECT {sql};', params)
    result, *__ = cursor.fetchone()

另一种选择可能是重建数据库使用的算法,但不同的数据库可以使用不同的算法,并且最终可能会改变主意。

© www.soinside.com 2019 - 2024. All rights reserved.