I am struggling to convert my sql query to a valid Postgres layer in QGIS with the help of Python. Here is what I tried:
SELECT * FROM test_geodb as k, vg250 as o WHERE ST_Within(ST_PointOnSurface(k.geom),o.geom) AND o.id = 71
When running the above code in pgAdmin4 I get 2 rows as a result as I except it. When I try to call the same statement inside my Qgis Plugin, I get an empty layer.
sql = "select k.pot_field, k.geom, k.id from test_geodb as k, vg250 as o WHERE ST_Within(ST_PointOnSurface(k.geom),o.geom) AND o.id = 71"
self.uri1.setDataSource("", "test_geodb", "geom", sql)
layer = QgsVectorLayer(self.uri1.uri(False), "testlayer", "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
While doing this:
self.uri1.setDataSource("public", "test_geodb", "geom", "w_speed = 5.75")
vlayer = QgsVectorLayer(self.uri1.uri(False) ,"layername2","postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
results in a correct selection and this:
self.db.setDatabaseName(self.uri1.database())
self.db.setUserName(self.uri1.username())
self.db.setPassword(self.uri1.password())
self.db.open()
self.query = QSqlQuery(self.db)
sql = "select k.pot_field, k.geom, k.id from test_geodb as k, vg250 as o WHERE ST_Within(ST_PointOnSurface(k.geom),o.geom) AND o.id = 71"
while self.query.next():
print self.query.record().value("geom")
#geom_query = query.record().value("geom")
gives me the geometries of my polygons as postgis geometries of the two rows. By reading here, here and here, I tried to solve my problem. I assume it has to do with the setting of the setDataSource
but I don't know how to fix it.
I am using Postgres 9.6, postgis 2.3 on windows 10 with QGIS 2.14