如何有效地将数据从geopandas保存到django(从有形转换为geodjango)?

时间:2019-05-24 21:50:13

标签: python django geodjango geopandas shapely

我正在处理带有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>

2 个答案:

答案 0 :(得分:1)

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

由于您的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,
    )

答案 1 :(得分:0)

更改此行

gdf ​​= gpd.read_file(“ some_data.geojson”)

gdf ​​= gpd.read_file(“ some_data.geojson”,driver =“ GeoJSON”)