PyQGIS – Get Feature ID of First Feature

feature-idpyqgis

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?

Best Answer

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.

Related Question