[GIS] Getting features by attribute using PyQgis

fields-attributespyqgis

How can I get a feature's geometry from selection by attribute?

For instance from a point layer I want to get the geometry by the field CODICE filter (CODICE = A001).

I tried with:

layer = QgsMapLayerRegistry.instance().mapLayersByName("My_layer")[0]
selection = layer.getFeatures(QgsFeatureRequest(QgsExpression("\"CODICE\" = 'A001'")))
geom = selection.geometry()

It doesn't work, and the python console error is:

AttributeError: 'QgsFeatureIterator' object has no attribute 'geometry'

Best Answer

Your approach is correct and working. However, the result you get back from layer.getFeatures is a QgsFeatureIterator and not a QgsFeature. You have potentially more than 1 feature in selection. You can simply iterate over your selection to get all the features:

for feature in selection:
    geom = feature.geometry()
    # do something with geom