Search code examples
djangogdalgeodjango

How to store GDAL objects in a geodjango Geometry object?


I have a GeoDjango GeometryField in my database:

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

I'm trying to load certain parts of shapefiles into my database.

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
    )

However, this returns this error:

Cannot set Place SpatialProxy (GEOMETRY) with value of type: <class 'django.contrib.gis.gdal.geometries.MultiPolygon'>

I'm not sure exactly how I have to transform this gdal.geometries.MultiPolygon object so that it can be stored in the database. I've tried using:

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

But this won't work.


Solution

  • I've had a look at the source of the GeoDjango LayerMapping utility, and it seems to convert GDAL geometries to WKT.

    You should be able to set the value with something like this:

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