QGIS Python Index – How to Generate an Index Field in QGIS Using Python for Optimized Data Management

fields-attributespyqgisqgis-2.18

I have some shapefiles for which I need to generate an index(int) field.

I tried using this function:

def add_index_to_layer(layer):
    fieldindex = layer.fieldNameIndex("index")
    if fieldindex >= 0:
        print "Layer " + layer.name() + " already has an index field"
        return False
    layer.dataProvider().addAttributes([QgsField("index", QVariant.Int)])
    layer.updateFields() # no idea if this is actually needed?
    fieldindex = layer.fieldNameIndex("index")
    i = 0
    layer.startEditing()
    for field in layer.fields():
        print field.name() # this shows the field "index" indeed exists
    for feature in layer.getFeatures():
        print feature.id(), feature["index"]
        feature.setAttribute("index", i)
        # this shows the value is being correctly set at this point
        print feature.id(), feature["index"] 
        i +=1
    layer.commitChanges()

The function runs just fine, the various print functions also show everything works as expected (values being set correctly).

However, when verifiyng by looking at the attribute table, the index field is created, but it always is empty/NULL.

Does anyone have an idea about what is going on? Are some of the changes pending where I expect them to be commited already? I thought layer.startEditing() and layer.commitChanges() would properly encapsulate feature field changes?

I am working with QGIS 2.18.0, and the script is created as a processing script.

Best Answer

Try replacing this line:

feature.setAttribute("index", i)

with this:

layer.changeAttributeValue(feature.id(), layer.fieldNameIndex("index"), i)