Skip to main content
 首页 » 编程设计

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

2025年05月04日14kuangbin

在我的项目中,我使用 PostgreSQL/PostGIS 作为数据库,使用 Django 和 django.contrib.gis配置。 现有表 pois 包含地理空间点 数据。以下是 SQL create 语句的摘录:

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

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

$ python manage.py inspectdb 

生成的模型如下所示:

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(),它应该是models.PointField()。或 models.GeometryField() .我都试过了。然后我在 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() 

此操作失败并输出以下堆栈跟踪:

/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 离开模型时,没有错误。然后输出字符串值。

请您参考如下方法:

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

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

正确:

DATABASES = { 
    'default': { 
        'ENGINE': 'django.contrib.gis.db.backends.postgis', # Here 
        'NAME': 'geodjango', 
        'USER': 'geo', 
        'PASSWORD': 'secret', 
        'HOST': 'localhost', 
        'PORT': '5432', 
    } 
} 

我在 the documentation 中监督了这个不知何故。感谢来自 #django irc channel 的 apollo13 为正确方向提供的建议。