TransWikia.com

Layer selectByExpression is Not select any feature even Expression is right why?

Geographic Information Systems Asked on September 29, 2021

I am trying select the features by expression if i pass query as string its working but if pass variable is not return any result why.

WORKING CODE

InputFeatureLayer.selectByExpression(""S_CODE" = 'ORCHARD OR PLANTATION NOT WALLED' AND "CATEGORY" = 'ORCHARD'",QgsVectorLayer.SetSelection)
features=InputFeatureLayer.selectedFeatures()
print(len(features))

if i mention query like above its working fine but I created a query when I pass its throwing error whats wrong with this

CODE NOT WORKING

InputFeatureLayer=QgsVectorLayer(r'D:TempQgisshpqgis.shp',"qgis","ogr")
Spilt_fields=['S_CODE', 'CATEGORY']
for row in TotalFeatures:
  qry='"'
  for field in Spilt_fields:
     print(field)
     if qry!='"':
        qry+=" AND "
     qry+='"{0}" = '{1}''.format(str(field), str(row.attribute(field)))
  qry+='"'
  print(qry)#it printing ""S_CODE" = 'ORCHARD OR PLANTATION NOT WALLED' AND "CATEGORY" = 'ORCHARD'"
  InputFeatureLayer.selectByExpression(qry,QgsVectorLayer.SetSelection)
  features=InputFeatureLayer.selectedFeatures()
  print(len(features)) # it return 0

What is the issue with the query?

One Answer

I was able to parse the expression in your code by removing the outer enclosing quotes (initialising the qry object as an empty string like qry = '') and removing the backslashes before the double quotes around the field names in the formatted string.

Try with the adjusted code snippet below:

InputFeatureLayer = QgsVectorLayer(r'D:TempQgisshpqgis.shp',"qgis","ogr")
Spilt_fields=['S_CODE', 'CATEGORY']
for row in TotalFeatures:
    qry = ''
    for field in Spilt_fields:
        print(field)
        if qry != '':
            qry += ' AND '
        qry += '"{0}" = '{1}''.format(str(field), str(row.attribute(field)))
    print(qry)
    InputFeatureLayer.selectByExpression(qry,QgsVectorLayer.SetSelection)
    print(InputFeatureLayer.selectedFeatureCount())

However taking an analytical view, I would point out that what this actually does is simply selects in turn every feature in the TotalFeatures iterable object which I assume is all features in the layer, replacing the previous selection, finally leaving the last feature selected. I am struggling to think of a use case for this logic.

Correct answer by Ben W on September 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP