I'm searching how to join two layers using PyQGIS.
I found a few solutions on this forum, and I specifically tried to follow the solution given here : How to use QGIS Graphical Modeller to join specific fields?
The displayed interface which offers a choice in the target/join layer and target/join field is perfect !
This solution was given 7 years ago, many things have changed since.
Here the original code :
##Join_layers=name
##Target_layer=vector
##Join_layer=vector
##Target_field=Field Target_layer
##Join_field=Field Join_layer
from qgis.core import QgsVectorJoinInfo
layer_1 = processing.getObject(Target_layer)
layer_2 = processing.getObject(Join_layer)
field_1=Target_field
field_2=Join_field
joinObject = QgsVectorJoinInfo()
joinObject.joinLayerId = layer_2.id()
joinObject.joinFieldName = Join_field
joinObject.targetFieldName = Target_field
layer_1.addJoin(joinObject)
First I had an error on this : QgsVectorJoinInfo
Here: https://qgis.org/api/classQgsVectorLayerJoinInfo.html,
we can see it changed for QgsVectorLayerJoinInfo
So I tried replacing QgsVectorJoinInfo with QgsVectorLayerJoinInfo.
But now I have this error :
"NameError: name 'processing' is not defined"
Traceback (most recent call last): File "C:\PROGRA~1/QGIS32~1.3/apps/qgis/./python/plugins\processing\script\ScriptEditorDialog.py", line 228, in runAlgorithm exec(self.editor.text(), _locals) File "", line 9, in NameError: name 'processing' is not defined
Since I don't know what I'm doing, I'm not sure changing random thing as I find infomation on the internet will work.
I also checked this solution : Joining table field with shapefile using PyQGIS and others sites like https://python-forum.io
I never worked with Python, I have literally no idea of how I can make it work.
This issue is old now; maybe I'm not supposed doing it that way?
I'm open to a better solution if you know how to automatically join 2 layers, without using the "add vector join" option in the layer's properties and without creating a new layer.
Modified code :
##Join_layers=name
##Target_layer=vector
##Join_layer=vector
##Target_field=Field Target_layer
##Join_field=Field Join_layer
from qgis import processing
layer_1 = processing.getObject(Target_layer)
layer_2 = processing.getObject(Join_layer)
field_1=Target_field
field_2=Join_field
joinObject = QgsVectorLayerJoinInfo()
joinObject.joinLayerId = layer_2.id()
joinObject.joinFieldName = Join_field
joinObject.targetFieldName = Target_field
layer_1.addJoin(joinObject)
The error is:
Traceback (most recent call last): File "C:\PROGRA~1/QGIS32~1.3/apps/qgis/./python/plugins\processing\script\ScriptEditorDialog.py", line 228, in runAlgorithm exec(self.editor.text(), _locals) File "", line 9, in AttributeError: module 'qgis.processing' has no attribute 'getObject'
ogrlibrary in another language would be easier for you – Ian Turton Mar 03 '22 at 08:34