Tuesday, 26 September 2017

Selecting column like Primary Key in View from PostGIS using PyQGIS?


Postgresql doesn't support Primary Key in views. When I load a postGIS view in QGIS "manually", I can choose the column that will be the Primary Key, but I would like to know if I can select a column as Primary Key when I load it using pyQGIS script.



Answer



I have found the answer reading the QGIS API


This is the method:


void QgsDataSourceURI::setKeyColumn (QString column )

this is my example:


uri = QgsDataSourceURI()

uri.setConnection('localhost', '5432', '-mydatabase-', '-myowner-', '-mypasswd-')
uri.setDataSource('public', 'parcelas', 'the_geom')
#public: schema, parcelas: the view, the_geom: spatial column
uri.setKeyColumn('id') #name of my primary key

vlayer = QgsVectorLayer(uri.uri(), '-name_of_the_layer-', 'postgres')
if vlayer:
print "All Ok!"

QgsMapLayerRegistry.instance().addMapLayer(vlayer)

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