1
|
|
2
|
|
3
|
from qgis.core import (
|
4
|
QgsVectorLayerJoinInfo, QgsVectorLayer, QgsField, QgsFeature,
|
5
|
edit, QgsProject)
|
6
|
from PyQt5.QtCore import QVariant
|
7
|
|
8
|
|
9
|
layer_1 = QgsVectorLayer('Point?crs=epsg:21781', 'layer_1', 'memory')
|
10
|
|
11
|
with edit(layer_1):
|
12
|
layer_1.addAttribute(QgsField('id', QVariant.Int))
|
13
|
layer_1.addAttribute(QgsField('column_a', QVariant.String))
|
14
|
layer_1.addAttribute(QgsField('column_b', QVariant.String))
|
15
|
feat = QgsFeature()
|
16
|
feat.setAttributes([1, 'A1', 'B1'])
|
17
|
layer_1.addFeature(feat)
|
18
|
|
19
|
|
20
|
QgsProject.instance().addMapLayer(layer_1)
|
21
|
|
22
|
|
23
|
layer_2 = QgsVectorLayer('Point?crs=epsg:21781', 'layer_2', 'memory')
|
24
|
|
25
|
with edit(layer_2):
|
26
|
layer_2.addAttribute(QgsField('id', QVariant.Int))
|
27
|
feat = QgsFeature()
|
28
|
feat.setAttributes([1])
|
29
|
layer_2.addFeature(feat)
|
30
|
|
31
|
|
32
|
QgsProject.instance().addMapLayer(layer_2)
|
33
|
|
34
|
|
35
|
|
36
|
join = QgsVectorLayerJoinInfo()
|
37
|
join.setJoinLayer(layer_1)
|
38
|
join.setJoinFieldName('id')
|
39
|
join.setTargetFieldName('id')
|
40
|
join.setJoinFieldNamesSubset(['column_a', 'column_b'])
|
41
|
layer_2.addJoin(join)
|
42
|
|
43
|
|
44
|
assert next(layer_2.getFeatures()).attribute(
|
45
|
'layer_1_column_a') == 'A1', 'Join (same order) Failed'
|
46
|
|
47
|
|
48
|
layer_2.removeJoin(layer_1.id())
|
49
|
|
50
|
|
51
|
|
52
|
join = QgsVectorLayerJoinInfo()
|
53
|
join.setJoinLayer(layer_1)
|
54
|
|
55
|
join.setJoinFieldName('id')
|
56
|
join.setTargetFieldName('id')
|
57
|
join.setJoinFieldNamesSubset(['column_b', 'column_a'])
|
58
|
layer_2.addJoin(join)
|
59
|
|
60
|
|
61
|
assert next(layer_2.getFeatures()).attribute(
|
62
|
'layer_1_column_a') == 'A1', 'Join (different order) Failed'
|