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.
1 Answer 1
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:
-
1Works very well. Thank you for providing a very clear answer!BritishSteel– BritishSteel2023年11月01日 15:04:33 +00:00Commented Nov 1, 2023 at 15:04
Explore related questions
See similar questions with these tags.