test_qgis2.py

Mario Baranzini, 2018-02-27 07:12 AM

Download (1.75 KB)

 
1
# coding: utf-8
2

    
3
from qgis.core import (
4
    QgsVectorJoinInfo, QgsVectorLayer, QgsField, QgsFeature,
5
    QgsMapLayerRegistry, edit)
6
from qgis.PyQt import QVariant
7

    
8
# Create layer_1
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
# add layer to the legend
21
QgsMapLayerRegistry.instance().addMapLayer(layer_1)
22

    
23
# Create layer_2
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
# add layer to the legend
34
QgsMapLayerRegistry.instance().addMapLayer(layer_2)
35

    
36
# Join the layers with the subset filds in the same order than the joined
37
# layer
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
# Verify the result
46
assert layer_2.getFeatures().next().attribute(
47
        'layer_1_column_a') == 'A1', 'Join failed'
48

    
49
# Remove the join
50
layer_2.removeJoin(layer_1.id())
51

    
52
# Join the layers with the subset filds in a different order than the joined
53
# layer
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
# Verify the result
62
assert layer_2.getFeatures().next().attribute(
63
        'layer_1_column_a') == 'A1', 'Join failed'