4

How do I get a list of fields that have been joined to a layer, or how can I check if a specific field has been joined?

In older versions there seemed to be field.source(), but this is not available anymore.

I am not performing the join via PyQGIS. The join is done manually and I would just like to use PyQGIS to detect which fields have been joined.

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Oct 31, 2023 at 16:26

1 Answer 1

6

One can detect which fields have been joined by means of the QgsFields class and its method fieldOrigin:

Returns the field's origin (value from an enumeration).

from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName("points")[0]
joined_fields = []
if len(layer.vectorJoins()) > 0:
 
 fields = layer.fields()
 
 for field in fields:
 field_name = field.name()
 indx = fields.indexOf(field_name)
 
 if fields.fieldOrigin(indx) == fields.OriginJoin:
 # or if fields.fieldOrigin(indx) == 2:
 joined_fields.append(field_name)
 
print(joined_fields)

The above code will result in a list of fields that have been joined to a layer. In my case it will be:

['month', 'month2', 'month3']

2 = OriginJoin means that this field comes from a joined layer.

OriginJoin Field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join)


References:

answered Oct 31, 2023 at 23:05
1
  • 1
    Works very well. Thank you for providing a very clear answer! Commented Nov 1, 2023 at 15:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.