1

I have a line layer on which I want to run a filter within a python script. I am trying to achieve this via QgsExpression and QgsFeatureRequest.

Below you see the same filter that I want to apply in the python script as well: enter image description here

In my python script i have an id to search for. But before I can filter by id, I have to cut the From and To string from the id so that I get all id with the specified number. Then I apply a request which you see in the code snippet below. But I get no results. I am not entering the for loop which loops through the results:

# trim edgeid (cut From and To)
edgeid_trimmed = edgeid_out.replace('From','')
edgeid_trimmed = edgeid_trimmed.replace('To','')

# get azimuth of edge (graph)
filter_edgeid_exp = QgsExpression('\"id\" LIKE \" ' + edgeid_trimmed + '%\" ')
request2= QgsFeatureRequest(filter_edgeid_exp)
request2.setLimit(2)

for j,feat2 in inputGraph.getFeatures(request2):
    print "found edges with requested edgeid"
    if j == 0:
        edge1_id = feat2.attributes()[idx_edgeid]
    else:
        edge2_id = feat2.attributes()[idx_edgeid]

However, I do not believe the expression in the QgsExpression(...) is wrong. So what else could be the problem here?

2

In QGIS expressions, double quote are for fields, simple quotes are for strings.

In your case, I think you might replace by :

filter_edgeid_exp = QgsExpression('"id" LIKE \'' + edgeid_trimmed + '%\'')
  • tried that already, but does not work either. – applebrown Feb 12 at 8:06
  • Could you add a print(filter_edgeid_exp) after setting filter_edgeid_exp, and give the resulting string ? – J. Monticolo Feb 12 at 8:20
  • if I print the expression in your way (print(filter_edgeid_exp)), I get this: <qgis._core.QgsExpression object at 0x0000000047C9CF28> – applebrown Feb 12 at 8:23
  • okay, got it. I missed one space... thank you so much! – applebrown Feb 12 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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