Django LayerMapping:如何在保存到数据库之前过滤形状文件

时间:2020-01-28 21:43:51

标签: python django import shapefile geodjango

我有一个形状文件,我想使用Django-LayerMapping模块(Link to module)导入到django数据库中,因为它可以将空间数据转换为GeoDjango模型。根据{{​​3}}将形状文件导入数据库的有效方式如下:

lm = LayerMapping(table, path, mapping, transform=True , encoding='utf-8') # load shape-file
lm.save(verbose=True) # save entire file to db

但是在我的情况下,我要将形状文件数据导入到的表不是空的。我只想将尚未存在的那些行(或shape-file lingo中的功能)添加到db中。但是,LayerMapping仅提供一种将整个shape文件保存到db的方法,而不是单个条目的方法,在我的情况下,这将导致重复。

因此,我的问题是:如何在保存图层映射对象之前过滤它的条目?

直到现在,我还考虑了两种可能的解决方案:

  1. 过滤层映射对象中的条目,并使用提供的.save()方法保存整个对象。但是我不知道如何从图层映射对象中删除单个条目。

  2. 遍历图层映射对象中的所有条目,并检查每个条目是否已存在于数据库中,仅在不存在时保存。但是,我找不到用于将单个条目保存到数据库的层映射方法。可以自己读取属性并创建对象,但随后我将无法访问坐标转换,这是使用图层映射模块的最初原因。

因此问题仍然存在:在保存之前,如何过滤此图层映射对象?

1 个答案:

答案 0 :(得分:0)

unique参数值得尝试使用LayerMapping,它是:

将其设置为给定模型的名称或名称元组,将创建仅对给定名称唯一的模型。来自每个要素的几何将被添加到与唯一模型关联的集合中。强制将交易模式设置为'autocommit'

在已有unique名称的情况下检查code executed,我们可以看到它试图将给定的几何图形追加到任何现有记录中:

if self.unique:
    # If we want unique models on a particular field, handle the
    # geometry appropriately.
    try:
        # Getting the keyword arguments and retrieving
        # the unique model.
        u_kwargs = self.unique_kwargs(kwargs)
        m = self.model.objects.using(self.using).get(**u_kwargs)
        is_update = True

        # Getting the geometry (in OGR form), creating
        # one from the kwargs WKT, adding in additional
        # geometries, and update the attribute with the
        # just-updated geometry WKT.
        geom_value = getattr(m, self.geom_field)
        if geom_value is None:
            geom = OGRGeometry(kwargs[self.geom_field])
        else:
            geom = geom_value.ogr
            new = OGRGeometry(kwargs[self.geom_field])
            for g in new:
                geom.add(g)
            setattr(m, self.geom_field, geom.wkt)
    except ObjectDoesNotExist:
        # No unique model exists yet, create.
        m = self.model(**kwargs)

如果这符合您的功能需求,那么您可以尝试以下独特选项:

lm = LayerMapping(
    table, 
    path, 
    mapping, 
    transform=True , 
    unique=('field_name_1', 'field_name_2', ...), 
    encoding='utf-8'
)

如果以上内容都不适合您的项目需求,那么您提到的选项将可以正常工作。

相关问题