1

I need a list of all values of a certain field in a QGIS dataset. To get this, I am using

  for festure in layer.getFeatures():
     value=feature[fieldname]

This is kind of working, but I have two issues with it, they may have the same solution:

  1. I want the data sorted by id, it seems to me that some of the points are not coming in the correct order.
  2. It seems rather slow. I have a dataset with a few thousand records and it uses several seconds to go through it.

(the base dataset is a PostGIS table if that matters)

So I have these questions:

  1. Is there any way to sort the data returned by getFeatures()?
  2. Is there any way to speed up getFeatures() or
  3. Should/could I use any other way of getting all values from a field?
1

Based on the article Fran Raga linked to (nyalldawson.net/2016/10/speeding-up-your-pyqgis-scripts ), I did the following:

First:

request=QgsFeatureRequest().addOrderBy('Id')
iter=layer.getFeatures(request)
for festure in iter:
   value=feature[fieldname]

This made the features come sorted in the order I wanted them. According to the article, this should also speed it up, but I did not notice any difference (I did not do any formal tests for speed)

Then I rewrote the featurerequest to only return the field I needed:

request =  QgsFeatureRequest().addOrderBy('Id').setFlags(QgsFeatureRequest.NoGeometry).setSubsetOfAttributes(['id'], layer.fields() )

This speeded it up significantly, that is, from having to wait for a long time to get the results as quickly as I was able to handle it.

I do believe that the most important thing here is the NoGeometry flag, but again, I have not tested that either. The lastest iteration gives me what I need as soon as I need it.

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.