I am trying to create my first script in QGIS.
##Double attribute selection=name
##Vector=group
##Selection_layer=vector
##First_field=field Selection_layer
##expression=string
##Second_field=field Selection_layer
from qgis.core import *
from PyQt4.QtCore import *
layer = Selection_layer
exp = QgsExpression("expression")
query_1 = "First_field" + expression
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query_1))
selected_ids = [k[Second_field] for k in selection]
ids = [] for feat in layer.getFeatures():
if feat[Second_field] in selected_ids:
ids.append(feat.id())
layer.setSelectedFeatures([l for l in ids])
Now i got error like that:
And I would like to have my inputs to look like that:
The script is related to my previous question: Selecting new records using values inside previous selected rows in QGIS?. Now I would like to change it to run in as a script. What I am trying to do is to select 2 fields from current layer. For the first field, I need to create a selection query. For the second one, I need to select only records which have the same number as the records from first field.
Can you help me?
1 Answer 1
You get that error because you were trying to iterate over a name (i.e. Selection_layer
) instead of a vector object. So you need to get it in this way for further using:
layer = processing.getObject(Selection_layer)
In your query_1
parameter, "First_field"
doesn't convert the field to a parameter because, in this way, you have just defined a field called "First_field"
(which doesn't exist). You may build the query in this way:
query_1 = '"'+ First_field +'" ' + expression
Finally, there were some other indentation errors, but I think they appeared when copying & pasting the code.
However, your final code should look like this (it worked for me):
##Double attribute selection=name
##Vector=group
##Selection_layer=vector
##First_field=field Selection_layer
##expression=string is NULL
##Second_field=field Selection_layer
from qgis.core import *
from PyQt4.QtCore import *
layer = processing.getObject(Selection_layer)
exp = QgsExpression(expression)
query_1 = '"'+ First_field +'" '+ expression
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query_1))
selected_ids = [k[Second_field] for k in selection]
ids = []
for feat in layer.getFeatures():
if feat[Second_field] in selected_ids:
ids.append(feat.id())
layer.setSelectedFeatures([l for l in ids])