1
|
|
2
|
|
3
|
from qgis.core import (
|
4
|
QgsVectorJoinInfo, QgsVectorLayer, QgsField, QgsFeature,
|
5
|
QgsMapLayerRegistry, edit)
|
6
|
from qgis.PyQt 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
|
|
16
|
feat = QgsFeature()
|
17
|
feat.setAttributes([1, 'A1', 'B1'])
|
18
|
layer_1.addFeature(feat)
|
19
|
|
20
|
|
21
|
QgsMapLayerRegistry.instance().addMapLayer(layer_1)
|
22
|
|
23
|
|
24
|
layer_2 = QgsVectorLayer('Point?crs=epsg:21781', 'layer_2', 'memory')
|
25
|
|
26
|
with edit(layer_2):
|
27
|
layer_2.addAttribute(QgsField('id', QVariant.Int))
|
28
|
|
29
|
feat = QgsFeature()
|
30
|
feat.setAttributes([1])
|
31
|
layer_2.addFeature(feat)
|
32
|
|
33
|
|
34
|
QgsMapLayerRegistry.instance().addMapLayer(layer_2)
|
35
|
|
36
|
|
37
|
|
38
|
join = QgsVectorJoinInfo()
|
39
|
join.joinLayerId = layer_1.id()
|
40
|
join.joinFieldName = 'id'
|
41
|
join.targetFieldName = 'id'
|
42
|
join.setJoinFieldNamesSubset(['column_a', 'column_b'])
|
43
|
layer_2.addJoin(join)
|
44
|
|
45
|
|
46
|
assert layer_2.getFeatures().next().attribute(
|
47
|
'layer_1_column_a') == 'A1', 'Join failed'
|
48
|
|
49
|
|
50
|
layer_2.removeJoin(layer_1.id())
|
51
|
|
52
|
|
53
|
|
54
|
join = QgsVectorJoinInfo()
|
55
|
join.joinLayerId = layer_1.id()
|
56
|
join.joinFieldName = 'id'
|
57
|
join.targetFieldName = 'id'
|
58
|
join.setJoinFieldNamesSubset(['column_b', 'column_a'])
|
59
|
layer_2.addJoin(join)
|
60
|
|
61
|
|
62
|
assert layer_2.getFeatures().next().attribute(
|
63
|
'layer_1_column_a') == 'A1', 'Join failed'
|