1

I am selecting the features by "Property_T" and its attribute is 'Open Land' and I want to add some attribute to "SS" field for same record. What is wrong?

from PyQt5.QtCore import QVariant

fn = "D:\Practice\Parcels.shp"
layer = iface.addVectorLayer(fn, '', 'ogr')

caps = layer.dataProvider().capabilities()

if caps & QgsVectorDataProvider.AddAttributes:
    res = layer.dataProvider().addAttributes([QgsField('SS', QVariant.String)])
    layer.updateFields()

query = "Property_T = 'Open Land'"
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.selectByIds([s.id() for s in selection])
iface.mapCanvas().setSelectionColor(QColor('Blue'))

features = layer.selectedFeatures()

for feat in features:
    if feat['Property_T'] == 'Open Land':
        with edit(layer):
            feat['SS'] = 'RR'
            layer.updateFeature(feat)
3
  • 3
    What are you trying to do and what is the problem with the code you are showing? If Property is Open Land SS field should be set to RR? Edit the question to clearify
    – BERA
    Nov 3, 2022 at 5:54
  • 4
    This is an instance of a "wall of code" post. They are treated harshly because they are perceived to state "I don't have the time to write a problem statement, just debug my code without me"
    – Vince
    Nov 3, 2022 at 5:57
  • sir iam selecting the features from parcel and field is Property type and its attribute is "open land" and i want to add the some attribute to SS field for same record Nov 3, 2022 at 6:12

1 Answer 1

3

Another option is to work with the selectedFeatureIds() and changeAttributeValue() methods of the QgsVectorLayer class.

ss_idx = layer.fields().lookupField('SS') #index of the "SS" field

with edit(layer):
    for feat_id in layer.selectedFeatureIds():
        layer.changeAttributeValue(feat_id, ss_idx, 'RR')

References:

Your Answer

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

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