【问题标题】:How to store GDAL objects in a geodjango Geometry object?如何将 GDAL 对象存储在 geodjango 几何对象中?
【发布时间】:2020-07-16 09:20:25
【问题描述】:

我的数据库中有一个 GeoDjango GeometryField:

class Place(models.Model):
    name = CharField()
    geometry = models.GeometryField()

我正在尝试将 shapefile 的某些部分加载到我的数据库中。

from django.contrib.gis.gdal import DataSource
datasource = DataSource("file.shp")
layer = datasource[0]

for each in layer:
    name = each.get("NAME") # To obtain the name
    ... (some more logic to add properties and validate which objects should be imported)
    Place.objects.create(
        name = name,
        geometry = each.geom
    )

但是,这会返回此错误:

无法使用类型值设置 Place SpatialProxy (GEOMETRY):

我不确定我必须如何转换这个gdal.geometries.MultiPolygon 对象,以便它可以存储在数据库中。我试过使用:

from django.contrib.gis.gdal import OGRGeometry
geometry = OGRGeometry(each.geom)

但这行不通。

【问题讨论】:

    标签: django gdal geodjango


    【解决方案1】:

    我查看了 GeoDjango LayerMapping utility 的来源,它似乎将 GDAL 几何转换为 WKT。

    您应该可以使用以下方式设置值:

    Place.objects.create(
        name = name,
        geometry = each.geom.wkt  # note the .wkt at the end
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-30
      • 2019-02-17
      • 1970-01-01
      • 2021-10-15
      • 2020-09-30
      • 1970-01-01
      • 2019-09-03
      • 2023-03-31
      相关资源
      最近更新 更多