3

I wish to join one field from a shapefile to another shapefile within the QGIS graphical modeler. I am aware that there is a 'Join attributes table' algorithm but this joins all of the fields from the shapefile.

Outside of the graphical modeler, I can use the Joins process in the layer properties but I would much rather be able to utilise this function within my models.

  • Is it possible to have the Target Layer be a variable? For example: - Active Layer Name: 012_Layer - Target Layer: 012_moreDetails - *Target Layer Variable: LEFT(@layer_name,3)||'moreDetails' This way it can be used in the Processing Modeler as long as layer names are consistent. – Peter B. Perkins Feb 16 at 17:42
  • If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. – underdark Feb 16 at 18:08
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review – BERA Feb 16 at 19:17
4

You can achieve this by creating a custom script in the Processing Toolbox which you can then add to your modeler. To create one:

Processing Toolbox > Scripts > Tools > Create new script

Then add the following code:

##Join_layers=name
##Target_layer=vector
##Join_layer=vector
##Target_field=Field Target_layer
##Join_field=Field Join_layer

from qgis.core import QgsVectorJoinInfo

layer_1 = processing.getObject(Target_layer) 
layer_2 = processing.getObject(Join_layer) 

field_1=Target_field
field_2=Join_field
joinObject = QgsVectorJoinInfo()
joinObject.joinLayerId = layer_2.id()
joinObject.joinFieldName = Join_field
joinObject.targetFieldName = Target_field
layer_1.addJoin(joinObject)

Make sure it is saved in C:\Users\You\.qgis2\processing\scripts for it to be available in the Processing Toolbox (you may need to close the script for the toolbox to update itself).

When you run the script, it should look like this:

Join script

where the user can choose the layers and fields to join. This has been tested in the QGIS modeler using QGIS 2.12.3-Lyon.

  • Where does the output from this script go when used in a graphical model? – Sorbus Jan 10 '18 at 22:26
  • 1
    @Sorbus - There is no output in this script, it was only used to join two layers. You will need to include an output parameter (e.g. ##output=output vector and include some logic to save the result as a new layer :) – Joseph Jan 11 '18 at 10:14

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.