2

I would like to filter a column coming from a layer with the command layer.selectByExpression().

I would like to leave the name of the column as a variable (not fixed). I made a conditions inside the column and its works very well, but I can't enter the column name as a variable.

That is the function which I am using:

layer.selectByExpression('\"column_name\"{}'.format(condition))

and here is my code:

class Layer_filter:
def __init__(self, name_layer, name_column, condition):
    self.name_layer = name_layer
    self.name_column = name_column
    self.condition = condition
    layer = QgsProject.instance().mapLayersByName(self.name_layer)[0]
    iface.setActiveLayer(layer)
    layer.selectByExpression('\"column_name"{}'.format(self.condition), QgsVectorLayer.SetSelection)

Taras
  • 32,823
  • 4
  • 66
  • 137

1 Answers1

1

I hope I got the gist of the question correctly. Please, try this:

layer = QgsProject.instance().mapLayersByName('layer')[0]

target_field = 'Type' #layer.attributeDisplayName(1) condition = 'Type 2'

if target_field in layer.fields().names(): layer.selectByExpression(f""{target_field}"='{condition}'")


References:

Taras
  • 32,823
  • 4
  • 66
  • 137