Thursday 7 June 2018

pyqgis - postGIS views, qGIS, qGIS python console


Using a win 7 machine, I have been revising tables in postGIS, then looking at the results in qGIS: with following script and run it in the qGIS python console.



import random
uri = QgsDataSourceURI()
myLayer = "layer_name"
myPrimaryKey = "the_key_name"

uri.setConnection("localhost","5432","database_name","user","password")
uri.setDataSource("public",myLayer,"geom","",myPrimaryKey)
vlayer= QgsVectorLayer(uri.uri(),myLayer+str(random.randrange(0,600)),"user")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

The problems I am running into are twofold:



  1. Sometimes if I do not change the name of the table, the above script does nothing. (The random # is there so that I can see if the script has added a layer and with a new name.)

  2. More importantly, the above script rarely works with postgis "views," meaning that each time I want to revise a table, I must first drop it. I'd rather be replacing views. The problem relates to this line:




uri.setDataSource("public",myLayer,"geom","","apn")

It let's me specify a schema, "public;" but I cannot figure out a way to say whether a table falls under the next level, namely postGIS tables or postGIS views. If I could do this, I would then be able to specify the name of the view. Yes, DBManager is "aware" of postGIS views. But I would like to know if the qGIS python console can work with postGIS views.



Answer



The only difference I can think of with a table or view is that with a table, QGIS knows what to use for primary key because it can infer it from the table primary key constraints. With a view, since you can't specify a primary key, you have to give it a name of a field to use.


I assume you are saying apn should be the primary key. If apn is duplicated in your view (multiple records have same apn) or does not exist, I think qGIS throws up an error cause it can't deal with duplicate keys and has to have a key.


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...