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
  • 32,823
  • 4
  • 66
  • 137
BritishSteel
  • 6,637
  • 4
  • 38
  • 64

1 Answers1

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:

Taras
  • 32,823
  • 4
  • 66
  • 137