如何从 Django 访问 postgis 数据库中的一个点?

How to access a point in postgis database from Django?

我正在尝试使用 django / postgis 从我的数据库中获取点(纬度经度坐标),但是我 运行 遇到了这个我无法理解的错误:

django.db.utils.ProgrammingError: cannot cast type point to bytea
LINE 1: ...lon_id", "lat_lon"."house_id", "lat_lon"."lat_lon"::bytea FR...

我的数据库是这样的:

我这样设置我的模型 (models.py):

class LatLon(models.Model):
    lat_lon_id = models.AutoField(primary_key=True)
    house = models.ForeignKey(Houses, models.DO_NOTHING)
    lat_lon = models.PointField()

    class Meta:
        managed = False
        db_table = 'lat_lon'
    
    @property
    def lat_lng(self):
        return(list(getattr(self.lat_lon, 'coords', []))[::-1])

并创建列表视图 (views.py):

class LatlonList(ListView):
    queryset = LatLon.objects.filter(lat_lon__isnull=False)

最后我的 urlpatterns 看起来像这样:

urlpatterns = [
    path("", views.home, name="home"),
    path("hello/<name>", views.hello_there, name="hello_there"),
    path("about/", views.about, name="about"),
    path("contact/", views.contact, name="contact"),
    path("log/", views.log_message, name="log"),
    path("test_page/", views.LatlonList.as_view(template_name = 'test_page.html'), name="test_page"),
    path('map/', views.EntryList.as_view()),

我从错误中猜想 Django 试图将我的点转换为 bytea 数据类型,但我在模型中明确指定它们是点 (Pointfield)。

我是 django 的新手,所以 responses/hints 不胜感激!

感谢 geozlot 的评论,我找到了解决方案。

我选择使用 sql 语句向数据库添加几何列:

SELECT AddGeometryColumn('lat_lon', 'lat_lon', 4326, 'POINT', 2, true)

接下来,我可以使用以下方法将 PostGIS 的几何点写入此列;

ST_SetSRID(ST_MakePoint(%s, %s), 4326))

其中 %s 是经度和纬度的占位符。