1

Is it possible to, through Python, to create the relations that it's possible to create in Layers/Properties/Fields/Relations, and if so how? I first thought these were saved in the styles, but that was not the case.

asked Mar 24, 2014 at 8:02

1 Answer 1

3

Yes, that is possible:

rel = QgsRelation()
rel.setReferencingLayer( 'child_layer_id' )
rel.setReferencedLayer( 'parent_layer_id' )
rel.addFieldPair( 'fk_field', 'pk_field' )
rel.setRelationId( 'my_relation' )
rel.setRelationName( 'Related Features' )
# rel.isValid() # It will only be added if it is valid. If not, check the ids and field names
QgsProject.instance().relationManager().addRelation( rel )

For inclusion in the layer style, please open a feature request on the issue page.

answered Mar 24, 2014 at 8:40
5
  • I can't find the QgsRelation class in QGIS API Documentation. Is it not documented yet? Commented Mar 24, 2014 at 14:03
  • 1
    Your looking at the 2.0 API. The relation stuff is available from version 2.2: qgis.org/api/2.2/… Commented Mar 24, 2014 at 22:23
  • I've been at it, but despite heeding the tip about checking that the ids and field names, can't seem to get it to work. As a guide, I'm looking at the saved .qgs project file where the relations have been created via the UI, and used this as a guid for ids, field and layer names placement. Prior to this I've loaded all layers programmatically and can verify that they are within the Layer TOC. Using the Python console in QGIS I'm trying to create the relations I can see the .qgs project file, but the final relation is never valid. Am I missing something? Commented Mar 26, 2014 at 9:43
  • Make sure to use the layer's id and not its name. Use QgsMapLayerRegistry.instance().mapLayers() to check for layer ids and [f.name() for f in QgsMapLayerRegistry.instance().mapLayers()[layer id].pendingFields()] to check for a layer's fields. Commented Mar 26, 2014 at 12:49
  • Extremely grateful for the pointers... Commented Mar 26, 2014 at 14:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.