我正在处理带geopandas的GIS数据并将其存储在各种Django模型中。 geopandas在后台使用shapely,而Django不使用。

这是一些代码:

import geopandas as gpd
from django.contrib.gis.db import models

class MyModel(models.Model):
  geometry = models.PolygonField()
  name = models.CharField(max_length=255, null=False, unique=True)
  some_property = models.IntegerField()

gdf = gpd.read_file("some_data.geojson")
# ...do some stuff w/ gdf...

for data in gdf.to_dict("records"):
  name = data.pop("name")
  MyModel.objects.create_or_update(
    name=name,
    defaults=data,
  )


上面将失败,并显示以下错误:


  TypeError:无法将MyModel SpatialProxy(POLYGON)设置为以下类型的值:


除非我添加一些讨厌的代码,例如:

from django.contrib.gis.geos import fromstr, Polygon
data["geometry"] = Polygon(fromstr(str(data["geometry"])))


有什么方法可以避免这种情况,并直接从shapely映射到Django



编辑:

以下是一些值:

>> data["geometry"]
<shapely.geometry.polygon.Polygon object at 0x7fb374f41908>
>> str(data["geometry"])
'POLYGON ((-4.337076919429241 53.41842814531255, -4.336698521348041 53.4182242737367, ....))'
>> fromstr(str(data["geometry"]))
<Polygon object at 0x7fb3733d158e>

最佳答案

您的解决方案似乎没有您想像的那么棘手。

由于您的data['geometry']字段返回WKT字符串表示形式('POLYGON ((-4.337076919429241 53.41842814531255, ... ))),因此您可以避免fromstr步骤并将其直接传递给to a GEOSGeometry

from django.contrib.gis.geos import GEOSGeometry

polygon = GEOSGeometry('POLYGON ((-4.337076919429241 53.41842814531255, ... ))')


您还可以添加一些错误处理,而不必担心解决方案崩溃了:):

for data in gdf.to_dict("records"):
    name = data.pop("name")
    geometry_str = data.pop('geometry')
    try:
        geometry = GEOSGeometry(geometry_str)
    except (TypeError, ValueError) as exc:
        # If the geometry_str is not a valid WKT, EWKT or HEXEWKB string
        # or is None then either continue, break or do something else.
        # I will go with continue here.
        continue

    if geometry.geom_type != 'Polygon':
        # If the created geometry is not a Polygon don't pass it on MyModel
        continue

    MyModel.objects.create_or_update(
        name=name, geometry=geometry,
        defaults=data,
    )

关于python - 如何有效地将数据从geopandas保存到django(从有形转换为geodjango)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56299888/

10-12 21:09