如何从Django访问PostGIS数据库中的几何(点)字段?

2024-05-20 01:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中,我使用PostgreSQL/PostGIS作为数据库,并配置了^{}的Django。现有表pois包含地理空间数据。以下是SQL create语句的摘录:

CREATE TABLE pois
(
  ogc_fid serial NOT NULL,
  the_geom geometry(Point,900914),
  name character varying(254),
  -- ...

我用以下命令生成了Django模型:

^{pr2}$

生成的模型如下所示:

from django.contrib.gis.db import models

class POIs(models.Model):
    ogc_fid = models.AutoField(primary_key=True)
    the_geom = models.TextField(blank=True, null=True) # This field type is a guess.
    name = models.CharField(max_length=254, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'pois'

我添加以下字段,以使用GeoDjango特定实例覆盖默认管理:

objects = models.GeoManager()

现在,我想将the_geom = models.TextField()替换为正确的数据类型,它应该是^{}或{a3}。我都试过了。然后我在Python shell上测试模型:

$ python manage.py shell
Python 3.4.3 (default, Jul 28 2015, 18:20:59) 
In [1]: from berlin import models
In [2]: models.POIs.objects.first()

此操作失败,并输出以下stacktrace

/home/user/.virtualenvs/myproject/lib/python3.4/site-packages/django/contrib/ \
    gis/db/models/fields.py in select_format(self, compiler, sql, params)
     57         else:
     58             sel_fmt = '%s'
---> 59         if connection.ops.select:
     60             # This allows operations to be done on fields in the SELECT,
     61             # overriding their values -- used by the Oracle and MySQL

AttributeError: 'DatabaseOperations' object has no attribute 'select'

当我用models.TextField离开模型时,没有错误。然后输出字符串值。在


Tags: thedjangonamefrom模型ogctruedb
1条回答
网友
1楼 · 发布于 2024-05-20 01:52:27

中的数据库配置设置.py不正确:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'geodjango',
        'USER': 'geo',
        'PASSWORD': 'secret',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

正确:

^{pr2}$

不知怎么的,我在the documentation里监督过这件事。感谢来自irc频道的apololol13向正确的方向提供建议。在

相关问题 更多 >