Removing table join using PyQGIS

attribute-joinspyqgisremovevector

I joined a table to a layer in QGIS using code from this thread: Joining layers with PyQGIS 3.
Now I would like to remove the join. How can I do it?

Best Answer

QgsVectorLayer possesses a method for that: removeJoin(joinLayerId: str).

So, if layer2 was initially joined to layer1, the code for removing the join may look like this:

from qgis.core import QgsProject

layer1 = QgsProject.instance().mapLayersByName("LAYER 1")[0]
layer2 = QgsProject.instance().mapLayersByName("LAYER 2")[0]

ids_of_joins_in_layer1 = [join.joinLayerId() for join in layer1.vectorJoins()]

if layer2.id() in ids_of_joins_in_layer1:
    layer1.removeJoin(layer2.id())
Related Question