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.

1 Answer 1


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!"


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.