0
vlayer = QgsVectorLayer("C:/yyy.shp", "yyy.shp", "ogr")
shp_uri ='C:/yyy.shp'
shp = QgsVectorLayer(shp_uri, 'yyy.shp','ogr')
QgsProject.instance().addMapLayer(shp)
csv_uri="file:///C:/xxx.csv?delimiter=,"
csv = QgsVectorLayer(csv_uri, "Output","delimitedtext")
QgsProject.instance().addMapLayer(csv)
shpField='Piezometer'
csvField='piezometerid'
joinObject = QgsVectorLayerJoinInfo()
joinObject.joinLayerId = csv.id()
joinObject.joinFieldName = csvField
joinObject.targetFieldName = shpField
joinObject.setUsingMemoryCache(True)
joinObject.setJoinLayer(csv)
shp.addJoin(joinObject)

In the joined shapefile, the fields of csv were added, but with NULL values. I have validated the shpField and csvField. Also validated the field type for both shpField and csvField. Is it the problem in my code or the implementation? If yes, please tell what it is.

1 Answer 1

3

You did not use setters for some content. There is maybe other remaining issues

shp_uri ='C:/yyy.shp'
shp = QgsVectorLayer(shp_uri, 'yyy.shp','ogr')
QgsProject.instance().addMapLayer(shp)

csv_uri="file:///C:/xxx.csv?delimiter=,"
csv = QgsVectorLayer(csv_uri, "Output","delimitedtext")
QgsProject.instance().addMapLayer(csv)

shpField='Piezometer'
csvField='piezometerid'
joinObject = QgsVectorLayerJoinInfo()
joinObject.setJoinLayerId(csv.id())
joinObject.setJoinFieldName(csvField)
joinObject.setTargetFieldName(shpField)
joinObject.setUsingMemoryCache(True)
joinObject.setJoinLayer(csv)
shp.addJoin(joinObject)

To debug, you can also try to manually make the join between your 2 files.

Then, after selecting your shp in the layer tree, inspect the equivalent of your joinObject with the following code

layer = iface.activeLayer()
joinObject = layer.vectorJoins()[0]
# Only using here method `joinFieldName` to inspect
# Use other methods listed at https://qgis.org/api/classQgsVectorLayerJoinInfo.html
# or by doing print(dir(joinObject))
print(joinObject.joinFieldName())
1
  • Thank you. It's working!!! May 11, 2021 at 16:01

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.