I'm trying to select features from a polygon layer where a specific string value ('yes') is found in a field called "result" and buffer them. My script can select features with a specific integer value in the "id" field and buffer them successfully, but doesn't appear to work for a string value in the "result" field; a buffer layer is produced but contains no features or geometry.
I'm relatively new to PyQGIS.
from qgis.core import *
from qgis.utils import *
# Set output file
output_fn = 'C:/Test/Buffer.shp'
# Set input layer to select features from
layer = iface.activeLayer()
# Select features by expression
#layer.selectByExpression('"result"=yes') # <- Desired selection doesn't work
layer.selectByExpression('"id"=2') # <- Undesired but produces a buffer of the specified feature
# Buffer selected feature(s)
processing.run("native:buffer",\
{'INPUT': QgsProcessingFeatureSourceDefinition(layer.id(), selectedFeaturesOnly=True, featureLimit=-1,\
geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid),\
'DISTANCE':5000,\
'SEGMENTS':99,\
'END_CAP_STYLE':0,\
'JOIN_STYLE':0,\
'MITER_LIMIT':2,\
'DISSOLVE':True,\
'OUTPUT': output_fn})
# Add output layer to layer tree
iface.addVectorLayer(output_fn, '', 'ogr')
Below is an image of the two features in the layer with the attribute table. Successfully buffered via layer.selectByExpression('"id"=2') version of the script.
Below is the non-result of using the layer.selectByExpression('"result"=yes') version of the script. In both scenarios, a Buffer layer is added to the Layer tree, though in this version it is empty. I can only narrow it down to there being a simple but elusive problem with the expression here because a selection has not occurred when looking at the attribute table. The key difference being that the first scenario involves an integer field, and this scenario a string field. Extension question (related): are there any good sources for constructing valid expressions with the selectByExpression method?