繁体   English   中英

如何从 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...

我的数据库如下所示:

经纬度数据库

我像这样设置我的 model (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 数据类型,但我在 model 中明确指定它们是点(Pointfield)。

我是 django 的新手,因此感谢您的任何回复/提示!

由于geozlot的评论,我找到了解决方案。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM