4

I'm trying to automate a workflow by making a PyQGIS script, but I haven't used Python before, so it's all a rollercoaster making it work. I noticed after some vector processing on a shapefile layer that my feature IDs changed from 0, 1, 2, 3,... to 1, 2, 3, 4,... in the resulting temporary layer. The question is why? And how can I find out which applies for a certain layer in PyQGIS?

I read somewhere that shapefiles don't have persistent IDs, so I thought it might have something to do with that (SHP vs temp layer). Is that it, or is there something more to it? I want my script to accept both types of input, and automatically figure out the FID of the first feature. How do I do that?

Let's say I have the following input layer

source = self.parameterAsSource(
   parameters,
   self.INPUT,
   context

Now what? How do I retrieve the first feature ID without knowing what it is?

1 Answer 1

4

Most basic, but maybe not most elegant solution is to just break the feature iteration after the first feature using break command:

source = self.parameterAsSource(parameters, self.INPUT, context)

first_fid = None
for feat in source.getFeatures():
    first_fid = feat.id()
    break

layer.getFeatures() will always iterate in order of the feature ids if you do not add an order by statement.

6
  • 3
    Or just first_id = next(source.getFeatures()).id().
    – Mayo
    Commented Jan 10, 2023 at 18:07
  • 1
    @Mayo worth posting it as the more elegant answer ;)
    – MrXsquared
    Commented Jan 10, 2023 at 18:09
  • Thank you! It works, and with @Mayo's suggestion even more elegantly so! My first thought was also to use .getFeatures(), but I didn't know how to index that. I couldn't find it in the PyQGIS documentation. Where should I look for documentation on these commands?
    – Joel
    Commented Jan 10, 2023 at 18:19
  • Thank you @Joel and MrXsquared!! Joel are you talking about where to find info about commands like next()?
    – Mayo
    Commented Jan 10, 2023 at 21:27
  • The getFeature() returns a feature iterator, (here what's a python iterator) so you can use the next() function to get each item at a time.
    – Mayo
    Commented Jan 10, 2023 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.