7

Under QGIS 1.8 on Windows 7 I have this problem with my pyArchInit plugin: I need to load on the map canvas my geometries from a PostGIS layer. Till the 1.7.4 version I use the method explained on the tutorial.

But I have to load also some Potgres view, and QGIS 1.8 need to know the column that I would like to use as ID.

How can I pass this value with PyQGIS and restore my plugin?

uri = QgsDataSourceURI()
# set host name, port, database name, username and password
uri.setConnection("localhost", "5432", "dbname", "johny", "xxx")
# set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")
vlayer = QgsVectorLayer(uri.uri(), "layer_name_you_like", "postgres")
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Jul 3, 2012 at 9:43

2 Answers 2

6

QgsDataSourceURI.setDataSource() has an additional fifth argument to specify the key column.

answered Jul 3, 2012 at 14:35
2

An update and an explicit example to complete @jef's answer :

uri = QgsDataSourceUri()
uri.setConnection("localhost", "5432", "myDatabase", "myUser", "myPassword")
uri.setDataSource("mySchema", "myTable", "myGeomField", aKeyColumn="myUniqueIdField")
vlayer = iface.addVectorLayer(uri.uri(False), "nameOfMyLayer", "postgres")

Adapt it with your database settings.

Source

answered Oct 27, 2020 at 12:53

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.