QGIS Auto Fill – Auto Fill Values in One Column Based on Another Column in QGIS

attribute-tablecolumnconditionalpyqgisqgis

There are three columns in the attribute table.

  • part, forest with both unique IDs and factor with three possible values (yes, no, check).
  • One forest contains many different part.

If the factor is changed to "yes" for one part of a forest, the column factor should be automatically updated to "yes" for all "parts" which are in the same "forest" and therefore share the same forest ID.

Of course there are ways to do this manually but an automatic solution would be great as the database is huge. So basically I am looking for an automatic fill for one column, but only for the lines which share the same value in a different column.

Best Answer

If I understand you correctly, part makes no difference, only forest?

Create a function in the python editor and call it with autofill() when you have set some row to yes:

def autofill():
    lyr = iface.activeLayer() #Make sure to click the layer name in table of contents
    yeses = {f['forest'] for f in lyr.getFeatures() if f['factor']=='yes'} #Find all forests with a yes in factor field
    factor_field_index = lyr.fields().indexFromName('factor') #Find field index of the factor field
    am = {} #A dictionary to hold the values to update
    if yeses: #If there are any forests in yeses set
        for f in lyr.getFeatures(): #For each feature in the table
            if f['forest'] in yeses: #Check if the features forest is in yeses set
                am[f.id()] = {factor_field_index:'yes'} #If it is, add it to the dictionary
        lyr.dataProvider().changeAttributeValues(am) #And update it

enter image description here

Related Question