Friday, 26 July 2019

Querying related tables in QGIS


I have a parcel layer and a table of property sales. I have the two tables related (it is a one-to-many relationship) in a QGIS project so that when you click on a parcel you see all the related sales information. Is there a way to query that related sales table and have it select the appropriate parcels directly in QGIS?


I have come up with a round-about way where I create a view in the Spatialite DB that the data is stored in but it is asking my end user a bit too much to be able to change the views parameters every time he needs a new sales map.




Answer



I have the same issue. If find an alternative solution based on a simple selection... (Duplicate issue i've made)


From the parent table, I retrieve a list of ID's (PK) and in the child table, I set a filter based on my list of ID's to my FK.


Important notice, I do not use the relationship, only a selection based on PK FK. There is an important performance issue on large tables.


Here a snippet.


li_id = []
layers = QgsMapLayerRegistry.instance().mapLayers()

for name, layer in layers.iteritems():
if name.lower().startswith('NAME OF MY PARENT TABLE'):

features = layer.selectedFeatures()
for f in features:
li_id.append(str(f.attribute('F_ID')))
cLayer = iface.mapCanvas().currentLayer() # (CHILD TABLE SELECTED IN TOC)
if len(li_id) ==1:
cWhere = """"F_ID" = '{0}'""".format(li_id[0])
else:
cWhere= """"F_ID" in {0}""".format(tuple(li_id))



expr = QgsExpression(cWhere)
it = cLayer.getFeatures( QgsFeatureRequest( expr ) )
ids = [i.id() for i in it]
cLayer.setSelectedFeatures( ids )
iface.showAttributeTable(iface.activeLayer())

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...