uri = QgsDataSourceUri()
uri.setConnection(aHost=self.db_conn.host, aPort=str(self.db_conn.port), aDatabase=self.db_conn.database, aUsername=self.db_conn.user, aPassword=self.db_conn.password)
query = f"select target_geometry.target_geometry_id, st_setSRID(target_geometry.target_geometry_geometry, 4326) as target_geometry_geometry from flight_planning.target_geometry where target_geometry.target_geometry_id = {selection[0].text()};"
uri.setDataSource('', f'({query})', 'target_geometry_geometry', '', 'target_geometry_id')
#uri.setDataSource("", "target_geometry", "target_geometry_geometry", f'target_geometry.target_geometry_id = {selection[0].text()}', 'target_geometry_id')
self.target_poly_layer = QgsVectorLayer(uri.uri(), "target_geometry", "postgres")
QgsProject.instance().addMapLayer(self.target_poly_layer)
The above code gives me this in the layer tree:
and in the properties, the source looks correct:
I have also tried the commented out line above as an alternative and it also does not work. If I don't try to use a query or a WHERE clause and just bring in the whole column from the table then it works just fine, but I only need part of the data.
I am using the answer from pyqgis - Load a PostgreSQL/PostGIS layer from a SQL query as a reference.
f"select ... from ... {my_where_condition_as_str};"
andmy_where_condition_as_str = f"where target_geometry.target_geometry_id = {selection[0].text()};"