1

Working with QGIS 3.34 (ltr) and PyQGIS, I'm trying to set up a relation between point layer and a No Geometry table.

I found out that the correct class to use is: relation.setStrength(QgsRelation.Composition).

The code seems to work, but, when I check on QGIS > Project > Property > Relation, I still get an 'Association' relationship. Do I need to add more relation set up?

Here is my full function:

def create_relation(parent_layer_name, child_layer_name, parent_field, child_field, 
relation_id, relation_name):

# Retrieve layers by name
   parent_layers = QgsProject.instance().mapLayersByName(parent_layer_name)
   child_layers = QgsProject.instance().mapLayersByName(child_layer_name)

   if not parent_layers or not child_layers:
      print(f"Layer '{parent_layer_name}' or '{child_layer_name}' not found.")
      return

    parent_layer = parent_layers[0]
    child_layer = child_layers[0]

   # Debug: Print layer IDs
   print(f"Parent Layer ID: {parent_layer.id()}, Child Layer ID: {child_layer.id()}")

   # Create a new QgsRelation object
   relation = QgsRelation()
   relation.setId(relation_id)
   relation.setName(relation_name)
   relation.setReferencedLayer(parent_layer.id())     # Parent layer
   relation.setReferencingLayer(child_layer.id())     # Child layer

   # Define the field pair (foreign key and primary key)
   relation.addFieldPair(child_field, parent_field)

   # Set relation strength to composition
   relation.setStrength(QgsRelation.Composition)

   # Validate and add the relation
   if relation.isValid():
      QgsProject.instance().relationManager().addRelation(relation)
      print(f"Relation '{relation_name}' created successfully.")
   else:
      print(f"Relation '{relation_name}' is not valid. Validation error: {relation.validationError()}")

1 Answer 1

1

The code I posted in my question is working correctly. I was using a custom .qml file that saves the style for my layer, including the relation as an association. However, I applied this custom style after creating the relation, which removed the "composition." The solution is to create the relation after applying the style.

Your Answer

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

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