[英]Django LayerMapping: How to filter shape-file before saving to database
我有一個形狀文件,我想使用 Django-LayerMapping 模塊( 鏈接到模塊)將其導入 django 數據庫,因為它將空間數據轉換為 GeoDjango 模型。 根據教程將形狀文件導入數據庫的香草方法如下:
lm = LayerMapping(table, path, mapping, transform=True , encoding='utf-8') # load shape-file
lm.save(verbose=True) # save entire file to db
但在我的情況下,我想導入形狀文件數據的表不是空的。 我只想將那些尚不存在的行(或形狀文件術語中的功能)添加到數據庫中。 但是,LayerMapping 只提供了一種將整個形狀文件保存到數據庫的方法,而不是單個條目,在我的情況下這會導致重復。
因此,我的問題是:如何在保存圖層映射對象之前過濾它的條目?
到現在為止,我想到了兩種可能的解決方案:
過濾圖層映射對象中的條目並使用提供的 .save() 方法保存整個對象。 但我不知道如何從圖層映射對象中刪除單個條目。
遍歷圖層映射對象中的所有條目,並檢查每個條目是否已存在於數據庫中,如果不存在則僅保存它。 但是,我沒有找到將單個條目保存到數據庫的圖層映射方法。 可以只讀取屬性並自己創建對象,但是我將無法訪問坐標轉換,這是使用圖層映射模塊的最初原因。
所以問題保持不變:如何在保存此圖層映射對象之前對其進行過濾?
一個值得嘗試使用LayerMapping
的選項是unique
參數:
將此設置為給定模型的名稱或名稱元組,將創建僅對給定名稱唯一的模型。 每個特征的幾何圖形將被添加到與唯一模型關聯的集合中。 強制事務模式為
'autocommit'
。
檢查在存在unique
名稱的情況下執行的代碼,我們可以看到它嘗試將給定的幾何圖形附加到任何現有記錄:
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'
)
如果以上不適合您項目的需要,那么您提到的選項將正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.