Starting from a QGIS project with many vector layers, I wish to load a file that extends the attribute table of one vector layer where a primary key matches. This is my first foray into QGIS and nothing works like I imagine.
The simplified code below successfully loads all the features (polygons) in the layer into a list.
zip_code_layer = QgsProject.instance().mapLayersByName('Zip_Codes')[0]
zip_code_feature_iter = zip_code_layer.getFeatures()
zip_code_features = []
for z in zip_code_feature_iter:
zip_code_features.append(z)
These are the fields
zip_code_features[0].fields().toList()
[<QgsField: OBJECTID (Integer)>, <QgsField: Zip_Code (String)>, <QgsField: Name (String)>, <QgsField: GlobalID (String)>, <QgsField: Shape__Are (Real)>, <QgsField: Shape__Len (Real)>]
When I try to extend the fields with append()
zip_code_features[0].fields().append(QgsField("test field", QVariant.String, "varchar", 64))
True
Despite the 'True' return value indicating success, nothing gets added to the feature's fields. Clearly, I am doing something wrong. I would be happy with any solution where I can use the Python API to add data to the attribute table from an external file.
my_feature.fields()you get a copy of the fields (QgsFieldsobject); you can of course callappend()on such object, but being a copy, it does not modify the original object. That's why you get theTruebut nothing changes. How to add fields and features to a layer is really well explained in the PyQGIS Cookbook. See this: https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#adding-and-removing-fields, and this: https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#add-features Let us know if you face troubles with that. – Germán Carrillo Oct 12 '21 at 19:26zip_code_layer.dataProvider().addAttributes([QgsField("test field", QVariant.String, "varchar", 64)])worked. I must say that this API is non-intuitive and convoluted at times. Is there an overview document that describes all the components of the application? I never would have even clicked on "dataProvider" to learn what it is because it sounded like a database thing. – Jonathon Parker Oct 13 '21 at 13:34