I have different qgis project with some layer and their datasource like ../my_path/my_file.shp. I need to insert this shp file to a remote db. For do it i use shapefile from PGeo module and it's work fine. But i need change layer datasource in qgs project with dbname= , host etc where schema_name is a name of qgis project, table_name is a layer id, and i need to maintain all layer's property. I tried to use:
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "mydb", "postgres", "postgres")
uri.setDataSource(str(schema_name),str(layer.id()),'the_geom')
layer = QgsVectorLayer(uri.uri(), str(layer.id()), "postgres")
QgsMapLayerRegistry.instance().addMapLayer(layer)
layer.reload()
print layer.source()
if not layer.isValid():
print "Layer is not valid"
project.write(QFileInfo(str(dir)+'/'+project_name))
But i always got "Layer is not valid" and nothing is changed on my qgis project. Is there another way to change layer datasource and save changes to the project? I see this solution but it doesn't work for me