I'm trying to write a plugin that among athor things adds a layer from a database. Here is my code:

        uri = QgsDataSourceUri()
        # set host name, port, database name, username and password
        uri.setConnection("geoerpdev2", "5432", "LAIS_SPACIAL", "postgres", "Passsword")
        # set database schema, table name, geometry column and optionally
        # subset (WHERE clause)

        uri.setDataSource("spacial", "parcels", "geom","cell_code=3030404")
        if uri:
            print (uri)

        vlayer = QgsVectorLayer(uri.uri(), "parcels", "postgres")
        if not vlayer.isValid():
            print (uri)
            print (vlayer)

When I change setDataSource as sugested to:

uri.setDataSource("spacial", "parcels", "geom","\"cell_code\"='3030404'")

Still nothing happens.

In the python console this is what is printed:

<qgis._core.QgsDataSourceUri object at 0x000002F5CA5C9EE8>
<qgis._core.QgsVectorLayer object at 0x000002F5CA5E8C18>
dbname='LAIS_SPACIAL' host=geoerpdev2 port=5432 user='postgres' password='Password' table="spacial"."parcels" (geom) sql=cell_code=3030404

This is the info about the layer when I load it manually: enter image description here

I based my code on this example here.

Can someone detect why nothing is loading?

  • Did my answer sort this out? – Alex Leith Apr 3 '18 at 0:44
  • It did not sadly:\ – Carmel Han Apr 3 '18 at 4:47
  • Oh, bugger... does it work without the filter? – Alex Leith Apr 3 '18 at 23:30
  • It'd be good to get the filter working, though! At lease we know that part is right ;-). – Alex Leith Apr 5 '18 at 23:13

Perhaps the quotes are important. Try it with this:

uri.setDataSource("spacial", "parcels", "geom","\"cell_code\"='3030404'")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.