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.


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.

| improve this answer | |
  • I can't find the QgsRelation class in QGIS API Documentation. Is it not documented yet? – user28233 Mar 24 '14 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/… – Jakob Mar 24 '14 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? – user28233 Mar 26 '14 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. – Matthias Kuhn Mar 26 '14 at 12:49
  • Extremely grateful for the pointers... – user28233 Mar 26 '14 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.