Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I'm trying to create and update a field and ,for now, just change it's value to 2.

Here is my code:

layer = qgis.utils.iface.activeLayer()
index = layer.fieldNameIndex("P")
# if index == -1: # field doesn't exist
caps = layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
   res = layer.dataProvider().addAttributes( [ QgsField("P", \
     QVariant.Double) ] )
layer.updateFields()
for feature in layer.getFeatures():
# None of these work
    index = layer.fieldNameIndex("P")
    feature["P"] = 2
    feature.setAttribute(index,(2.0))
    feature.attributes()[index] = 2
#################

layer.commitChanges()

But all I get is a new column filled with NULL values. I can't figure out where I'm making a mistake though.

EDIT:

It seems the actual value has been updated (last value) :

     feature.attributes()
 [28965.0, 209294.0, 43.0, 207459.0, NULL, u'HANOVER', u'AV', 3901.0, 4049.0, 3900.0, 4048.0, u'Hanover Av', u'LOCAL STR', NULL, NULL, u'LOCAL STREET', NULL, 0.0, 50.0, 50.0, 5436.0, 43.0, 25.0, 209294.0, NULL, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, NULL, 0.0, 0.0, 0.0, 0.0, 1, 2]

But in the shapefile, it still shows NULL.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

You have to enable editing on the layer:

layer.startEditing()

and update each feature after changing its attribute:

layer.updateFeature(feature)
share|improve this answer
    
Thanks a lot. so I figured that I also had to add "layer.updateFeature(feature)" and "layer.commitChanges()". Just one question: it takes a long time to execute "layer.updateFeature(feature)". any idea on how to do it faster, or once at the very end for all the features? –  Pep Mar 14 at 21:54
    
Also, I don't know the rules that well; may I edit your answer to add the other two lines? –  Pep Mar 14 at 22:07
    
Yes you can edit. –  Nathan W Mar 14 at 22:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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