2

I am using this code in the QGIS Python console to update a feature value. However, in order to get the feature value to change, I have to run it twice. Suggestions on why this is happening?

layer = iface.activeLayer()

layerFields = layer.fields()
fieldIndex = layerFields.indexFromName("February")
feature = layer.selectedFeatures()
featureID = feature[0].id()
label = 'G'
layer.startEditing()
layer.changeAttributeValue(featureID, fieldIndex, label)
layer.commitChanges()

print(fieldIndex)

for f in feature:
    print(f.attributes())

1st:

    exec(open('C:/..../AppData/Local/Temp/tmpb78pyjoe.py'.encode('utf- 8')).read())
    3
    [10, 440631, NULL, NULL]

2nd:

    exec(open('C:/..../AppData/Local/Temp/tmp_9u0wl9z.py'.encode('utf-8')).read())
    3
    [10, 440631, NULL, 'G']

1 Answer 1

4

You need to get your Features again, with the updated values. Otherwise you will get them from memory, where you stored it before you have done your changes. Add

feature = layer.selectedFeatures()

before you print the attribute values.

layer = iface.activeLayer()

layerFields = layer.fields()
fieldIndex = layerFields.indexFromName("February")
feature = layer.selectedFeatures()
featureID = feature[0].id()
label = 'G'
layer.startEditing()
layer.changeAttributeValue(featureID, fieldIndex, label)
layer.commitChanges()

print(fieldIndex)

feature = layer.selectedFeatures()

for f in feature:
    print(f.attributes())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.