I found the function setSubsetOfFields to filter fields in a layer in the PyGIS cookbook:


But it seems like that these function doesn't exist in QGIS 2.4. Neither has the layer a fields() function. There is only a setSubsetOfAttributes function.

I tried to use it like this:

layer = qgis.utils.iface.activeLayer()  
request = QgsFeatureRequest()
request.setSubsetOfFields(['id', 'name'], layer.fields())

features = layer.getFeatures(request)
for feature in features:
    print feature.attributes()

Am I using this wrong or is there another possibillitie to set a filter on the layer fields?

  • 1
    Use setSubsetOfAttributes(["id", "name"], layer.pendingFields()). The PyQGIS Cookbook will be updated. – lrssvt Oct 31 '14 at 16:17
  • Thank you, it worked. The attribute list I get looks like this [7045, u'Berlin', None, None]. Is there a possibility to get only a list of the two requested features? – Martin Nov 3 '14 at 8:30
  • There is a way in python: [attr for attr in feature.attributes() if attr is not None] – lrssvt Nov 3 '14 at 8:48
  • Thanks. I iterate over the list of fields and use attribute with the field name feature.attribute(field). Because if the attribute is a null value it will be not appended to the list. – Martin Nov 3 '14 at 9:13
  • Yeah, you also can get it by index from feature object like so: feature["field_name"] – lrssvt Nov 3 '14 at 9:22

Now I use this code to filter specific fields out of the layer attributes:

fields = ['id', 'name']
filterFields = []
features = layer.getFeatures()
for feature in features:
    attrs = [feature[field] for field in fields]

This generates a list containing the filtered attributes for every feature of a layer.

| improve this answer | |
  • You shouldn't do like that. By doing this, you are loosing performance as QGIS will fetch all attributes. Using QgsFeatureRequest, QGIS can reduce the amount of data returned by the query on the data provider side. It will take more time and memory. – etrimaille Oct 7 '16 at 9:55

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.