2

I'm trying to use Python to join a table to a vector layer within QGIS (v. 3.2.0)

Here is the script I use :

>>>root = QgsProject.instance().layerTreeRoot()
>>>ids = root.findLayerIds()
>>>target=QgsProject.instance().mapLayer(ids[1])
>>>print ("target :",target.id())
target : du_fl_pts_e154c28b_4812_41a2_9a78_bf95b7a97926
>>>layerToJoin=QgsProject.instance().mapLayer(ids[0])
>>>print("Layer to join :",layerToJoin.id())
Layer to join : TAXREF_9ab461d0_81d1_4095_b1d0_dce90b20600e
>>>lien = QgsVectorLayerJoinInfo()
>>>lien.targetFieldName = 'CD_REF'
>>>lien.joinLayerId = ids[0]
>>>lien.joinFieldName = 'CD_NOM'
>>>target.addJoin(lien)
True

But after the execution of this script, I have no join on my target layer.

Interesting fact : when I test the same script on the same layers/tables on QGIS 2.18.21 (just changing QgsProject -> QgsMapLayerRegistry and QgsVectorLayerJoinInfo -> QgsVectorJoinInfo) the join works.

Any idea why this doesn't work on QGIS 3?

1 Answer 1

2

You need to rename some of your functions as described in the API for the new QgsVectorLayerJoinInfo class in QGIS 3.

E.g.

  • targetFieldName() should now be setTargetFieldName()
  • joinLayerId() should now be setJoinLayerId()

etc.


So try using something like the following:

lien = QgsVectorLayerJoinInfo()
lien.setJoinFieldName('CD_NOM')
lien.setTargetFieldName('CD_REF')
lien.setJoinLayerId(layerToJoin.id())
lien.setUsingMemoryCache(True)
lien.setJoinLayer(layerToJoin)
target.addJoin(lien)

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.