pyQGIS – Troubleshooting pyQGIS QgsVectorLayer().isValid() Returning FALSE with Oracle Views

oracle-spatialpyqgis

This works perfectly fine with an Oracle TABLE but not with a VIEW. Why?

uri = QgsDataSourceURI()
uri.setConnection(host, port, db, username, pw)
uri.setWkbType(QGis.WKBPolygon)
uri.setDataSource(schema, table, geomcol)
vlayer = QgsVectorLayer(uri.uri(), table, 'oracle')
print vlayer.isValid()

..and returns TRUE. However, the same code does not work with a VIEW. Both TABLE and VIEW have correct entry in USER_SDO_GEOM_METADATA. All spatial tables in the database load correctly; none of the views do.
All spatial tables and views load correctly in QGIS using Layer->Add Layer->Add Oracle Spatial Layer. Is it meant to work only with tables or am I doing something wrong?

Best Answer

For VIEWS you have to define the column which uniquely identify features for the layer, try to add:

uri.setKeyColumn("your_unique_field")
Related Question