QGIS – Selecting and Updating Attribute Values Using Python Console

pyqgisqgisselect-by-attribute

I am working with Landusefc and Class columns (ref table).

What I want is: Selecting all water from "Class" and giving a value say '8' in the "Landusefc" column for these selected features.

Table looks like

Test table
I have tried the following code, it works till the selection part but doesn't seem to change the attribute value using the ChangeAttributeValue.

from qgis.core import *
import processing
layer=processing.getObject('test1')
query= ' "class" = \'Water\' '
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.setSelectedFeatures([k.id() for k in selection])

#using change Attribute to change the value of the selected feature

layer.startEditing()
for feat in selection:
     layer.changeAttributeValue(feat.id(), 5, 8)

layer.commitChanges()

Best Answer

SOLUTION 1:

You have to remove layer.setSelectedFeatures([k.id() for k in selection]).

Because selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query)) line gives you a QgsFeatureIterator, that's an iterator. When you use that iterator once, you reach the end of the iterator. Then, if you use it again, you get nothing.

In your case, when you use selection variable (it's an iterator now) in [k.id() for k in selection], you reach the end. If you use selection in for loop, since you are at the end of the iterator, you don't have any feature now. If you want to be certain, you can add a print("Foo") line to for loop.

SOLUTION 2:

Change for feat in selection: into for feat in layer.selectedFeatures():. This solution works only on QGIS 2.x.