3

I'm trying to load a table in QGIS layers tree using PyQGIS (see here for example). Said table has got a primary key with no null/duplicate entries; a geometry column (which is empty for now); and works perfectly fine when I load it using QGIS database manager.

But, when I try to load it using PyQGIS, the layer does not load correctly: there's a /!\ next to its name in QGIS layers tree, and print(myLayer.isValid()) returns False. And I can't figure out what is wrong with my code...

Here is my code so far (host, bdd, password etc.. have been defined as global variables earlier in the code):

uri = QgsDataSourceUri()
uri.setConnection(host, port, bdd, user, password, QgsDataSourceUri.SslDisable)
uri.setDataSource("ref", "grds_types_milieux","empty_geom","")
myLayer = QgsVectorLayer(uri.uri(), "grds_types_milieux", "postgres") 
QgsProject.instance().addMapLayer(myLayer)
Noura
3,4373 gold badges21 silver badges41 bronze badges
asked Apr 1, 2020 at 16:30
1

1 Answer 1

1

Made it work by :

  • recreating my table with the primary key column in first position
  • renaming my geometry column to "geom" (also, it's the last column; but I don't know if this matters)
  • giving the name of the primary key column in the code :

    uri.setDataSource("ref", "grds_types_milieux","geom","","id")

answered Apr 2, 2020 at 8:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.