5

I have vector data: enter image description here

And would like to iterate over the attribute table returning only two field values. Isn't there a way to limit the values returned by getFeatures so all attributes does not have to be read? This work but seems convoluted:

layer = iface.activeLayer()
fields_to_return = ['KKOD','KATEGORI']
for feat in layer.getFeatures():
    print([feat[f] for f in fields_to_return])

[414, 'Kommun']
[414, 'Kommun']
[414, 'Kommun']
...

In ArcGIS I would do:

with arcpy.da_SearchCursor(r'C:\data.gdb\ak_riks',fields_to_return) as cursor:
    for row in cursor:
        print(row)
6

You should "very often" use QgsFeatureRequest :

If you need only a subset of attributes, and also maybe you don't need the geometry, you can do something like:

expected_fields = ['KKOD', 'KATEGORI']
layer = iface.activeLayer()
indexes = [layer.fields().indexFromName(field) for field in expected_fields]

request = QgsFeatureRequest()
request.setFlags(QgsFeatureRequest.NoGeometry)
request.setSubsetOfAttributes(indexes)
for feature in layer.getFeatures(request):
    print(feature['KKOD'], feature['KATEGORI'])

You need to check your attributes index.

I really suggest you to read http://nyalldawson.net/2016/10/speeding-up-your-pyqgis-scripts/ This will highly speed up your scripts. Instead to query all attributes, with geometry, just query what you need in your scripts.

| improve this answer | |
7

From Docs, you can pass a QgsFeatureRequest to getFeatures()

https://qgis.org/pyqgis/3.0/core/Vector/QgsVectorLayer.html#qgis.core.QgsVectorLayer.getFeatures

QgsFeatureRequest describe the way you retrieve the QgsFeature You can use setSubsetOfAttributes (https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html#qgis.core.QgsFeatureRequest.setSubsetOfAttributes).

The QgsFeatureRequest object that can be pass to getFeatures() has a lot of options. There are describe in the docs. For example you can:

  • Filter features by an extent
  • Filter features by an expression (using QgsExpression)
  • Avoid fetching geometry to improve performance
  • get only a subset of attributes (it's your use case)
  • ...

Plus, all options can be chained (e.g., filter by extent and retrieving only some fields without geometry)

See : https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html

You can find some example using this here

| improve this answer | |

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.