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)

1 Answer 1

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:

4
  • in your code you write the name of the column and it is fixed by the function name_column = layer.attributeDisplayName(1). This function delivers the name of the second column. What I want to realize is to be able to enter a variable, which has to be equal to some name of a column, and with this value to be able to realize a condition. Commented Nov 4, 2022 at 13:02
  • yes, a user enters this variable Commented Nov 4, 2022 at 13:38
  • 1
    Thank you!. It has worked! Commented Nov 4, 2022 at 15:57
  • Always welcome!
    – Taras
    Commented Nov 4, 2022 at 18:14

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.