[GIS] Cannot load postgis layer from sql string in pyqgis

postgispyqgispythonqgissql

I'm trying to load a layer using the following code in qgis python console:

sql = "(select the_geom, ID from mytable)"
uri = QgsDataSourceURI()
uri.setConnection("localhost","5432","mydb","postgres","XXXX")
uri.setDataSource("myschema",sql,"the_geom","","ID")
vlayer = QgsVectorLayer(uri.uri(),"LayerName","postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

It doesn't add the layer but also doesn't return any error.

I'm using QGIS 2.4.0-Chugiak

Best Answer

The postgres provider requires integer datatypes (i.e. ones, that are internally handled as QVariant::Integer or QVariant::LongLong)

Integer:

  • int2
  • int4

LongLong:

  • int8
Related Question