[英]How to access a geometry (point) field in PostGIS database from Django?
In my project I am using PostgreSQL/PostGIS as the database and Django with django.contrib.gis
configured.在我的项目中,我使用 PostgreSQL/PostGIS 作为数据库和 Django 并配置了
django.contrib.gis
。 The existing table pois
contains geospatial point data.现有表
pois
包含地理空间点数据。 Here is a excerpt from the SQL create statement:以下是 SQL create 语句的摘录:
CREATE TABLE pois
(
ogc_fid serial NOT NULL,
the_geom geometry(Point,900914),
name character varying(254),
-- ...
I generated the Django model with the following command:我使用以下命令生成了 Django 模型:
$ python manage.py inspectdb
The generated model looks like this:生成的模型如下所示:
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'
I add the following field to overwrite the default manage with a GeoDjango specific instance:我添加以下字段以使用 GeoDjango 特定实例覆盖默认管理:
objects = models.GeoManager()
Now, I want to replace the_geom = models.TextField()
with the correct data type which should be either models.PointField()
or models.GeometryField()
.现在,我想用正确的数据类型替换
the_geom = models.TextField()
,该类型应该是models.PointField()
或models.GeometryField()
。 I tried both.我两个都试了。 Then I test the model at the Python shell:
然后我在 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()
This fails and the following stacktrace is output:这失败并输出以下堆栈跟踪:
/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'
There is no error when I leave the model with models.TextField
.当我用
models.TextField
离开模型时没有错误。 Then the string value is output.然后输出字符串值。
The database configuration in settings.py was incorrect: settings.py 中的数据库配置不正确:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'geodjango',
'USER': 'geo',
'PASSWORD': 'secret',
'HOST': 'localhost',
'PORT': '5432',
}
}
Correct:正确的:
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis', # Here
'NAME': 'geodjango',
'USER': 'geo',
'PASSWORD': 'secret',
'HOST': 'localhost',
'PORT': '5432',
}
}
I have overseen this in the documentation somehow.我以某种方式在文档中监督了这一点。 Thanks to apollo13 from the
#django
irc channel for the advice into the right direction.由于从apollo13
#django
的意见进入右方向IRC频道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.