QGIS – Adding Addressing Layer in Field Calculator Using Python Script

pyqgispyqgis-3pythonqgisqgis-3

I am trying to use the field calculator in a Python script. I use a formula to calculate shortest distance between two polygons (layer_A, layer_B).
The formula for the field calculator works well when used directly on layer_A in QGIS. The formula is:

length(
    shortest_line(
        $geometry,
        geometry(get_feature('layer_B','fieldname',attribute('fieldname')))
        )
    )

The thing is I can’t figure out how to address the second layer_B in my Python script. I tried using a string to the file path like that:

fomular = '\'length(shortest_line($geometry,geometry(get_feature(\'' + 'path/to/layer_B' + '\',\"fieldname\",attribute(\'fieldname\')))))\''

The formula generates a new field in layer_A, but no distance is calculated. Also, Python gives no error. layer_B seems not to be addressed correctly. What am I doing wrong?

Best Answer

Your formula will work if you first make a QgsVectorLayer from the path and add the layers to the canvas. They can be removed immediately after the calculation for clean-up if needs be:

p = QgsProject.instance()

layer_A = QgsVectorLayer('path/to/layer_A', 'layer_A')  # the second argument is the layer name
layer_B = QgsVectorLayer('path/to/layer_B', 'layer_B')  # the second argument is the layer name

# add layers to canvas
p.addMapLayer(layer_A)
p.addMapLayer(layer_B)


formular = "length(shortest_line($geometry, geometry(get_feature('layer_B', 'fieldname',attribute('fieldname')))))"
calculated = processing.run("native:fieldcalculator", {'INPUT':layer_A, 'FIELD_NAME':'distance', 'FIELD_TYPE':0, 'FIELD_LENGTH':0, 'FIELD_PRECISION':0, 'FORMULA': formular, 'OUTPUT':'TEMPORARY_OUTPUT'})['OUTPUT']

p.addMapLayer(calculated)

# clean-up
p.removeMapLayer(layer_A)
p.removeMapLayer(layer_B)
Related Question