is it possible to use this GeoHash class directly without creating a model on a db?
e.g.:
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
GeoHash
[Django-doc] itself does not compute anything. Essentially it is just some abstract syntax tree node that translates to an SQL expression. So the algorithm is evaluated in the database, not by Django.
Is it possible to use this GeoHash class directly without creating a model on a db?
Yes, or at least kindoff. We could make a SELECT
query, and determine the geohash there, like:
You can use another model that has nothing to do with it to evaluate it, with:
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()
another option could be to reconstruct the algorithm the database uses, but different databases can use different algorithms, and could eventually change their mind.