I like to semiautomate my workflow.
I got always the same kind of geopackage with polygons and heat usages. I want to calculate the area of the polygons thus create a new field, calculate and write the area their and divide this by the heat usage in a second new cell.
I do not want a new file but create the new fields in the existing one.
When I run it the following message pops up. "Could not creat layer building ... Creating of data source failed".
I found "attach to layer" but here I need to state where the geopackage layer is again. I like to speed up the process.
Is there another way?
-
2I dont think it is possible using Field Calculator. You can use pyqgis thoughBera– Bera2025年01月21日 06:05:40 +00:00Commented Jan 21 at 6:05
-
So your problem is overwriting the input layer? I have models that overwrite a layer in a geopackage with newly created layer - using an expression to select the correct gpkg and layerSethinacan– Sethinacan2025年01月21日 08:10:19 +00:00Commented Jan 21 at 8:10
1 Answer 1
As @Bera mentioned, this is difficult to do using only the Model Builder / Field Calculator.
With PyQGIS it is quite easy though:
# Get the active layer
layer = iface.activeLayer()
# Start editing the layer
layer.startEditing()
# Add new fields
layer.addAttribute(QgsField('area', QVariant.Double))
layer.addAttribute(QgsField('area_over_heat', QVariant.Double))
# Update fields
layer.updateFields()
# Get the index of the new fields and heat_usage (adapt name according to your field name in the following)
area_idx = layer.fields().indexOf('area')
div_idx = layer.fields().indexOf('area_over_heat')
field1_idx = layer.fields().indexOf('heat_usage') # add more fields for other calculations
# Calculate area & area_over_heat for each feature
for feature in layer.getFeatures():
# Calculate area (in the layer's CRS units)
area = feature.geometry().area()
# Get field1 value
field1_value = feature.attributes()[field1_idx]
# Calculate division (handle potential division by zero)
if field1_value != 0:
div = area / field1_value
else:
div = None # or whatever value you want to use for division by zero
# Update the feature
layer.changeAttributeValue(feature.id(), area_idx, area)
layer.changeAttributeValue(feature.id(), div_idx, div)
# Commit changes to your layer
layer.commitChanges()
-
okay, I have no experience with pygis but I will try. thanks!BAE_23– BAE_232025年01月21日 09:59:24 +00:00Commented Jan 21 at 9:59