Only return listed column values

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


You should "very often" use QgsFeatureRequest :

  • https://qgis.org/api/classQgsFeatureRequest.html
  • https://qgis.org/pyqgis/master/core/QgsFeatureRequest.html

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.