0

The name of vectorlayer's unique-id fieldname can be technically any string ("ID","FID","OID","id_0", etc) and its position can be technically anywhere. So featureobject.fields().names()[0] is not 100% reliable.

How do I retrieve it via PyQGIS?

In the GUI it is shown in the 'Information' tab of the Layer Properties dialog.

enter image description here

1 Answer 1

1

I haven't tested fully, but maybe this:

lyr = iface.activeLayer()
pk_idx = lyr.primaryKeyAttributes()[0]
pk_name = lyr.fields()[pk_idx].name()

print(pk_name)
1
  • Thanks! The primaryKeyAttributes() returns a list. That implies there's also the possibility of using composite primary keys but I have never seen that in the orbit of QGIS. Interesting.
    – maxwhere
    Mar 3, 2023 at 15:46

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.