【问题标题】:How to access a geometry (point) field in PostGIS database from Django?如何从 Django 访问 PostGIS 数据库中的几何(点)字段?
【发布时间】:2015-12-07 01:04:36
【问题描述】:

在我的项目中,我使用 PostgreSQL/PostGIS 作为数据库和配置了 django.contrib.gis 的 Django。 现有表 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()

这会失败,并输出以下 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 离开模型时,没有错误。然后输出字符串值。

【问题讨论】:

    标签: python django postgis geodjango


    【解决方案1】:

    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 频道的 apollo13 提供正确方向的建议。

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 2022-10-05
      • 1970-01-01
      • 2013-10-24
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多