I have an existing geopackage layer in my QGIS project. I want to duplicate a feature on the layer via PyQGIS:
layer = iface.activeLayer()
layer.startEditing()
sourcefeat = next(layer.getFeatures()) # choose the very first feature, for instance
newfeat = QgsFeature()
newfeat.setGeometry(sourcefeat.geometry())
newfeat.setAttributes(sourcefeat.attributes())
layer.addFeature(newfeat)
layer.commitChanges()
I get an OGR error when committing changes: "failed to execute insert : UNIQUE constraint failed: layer.fid"
1 Answer 1
Found my own solution:
Geopackage provides an "fid" column as primary key in the attribute table when adding it to a QGIS project. On default, it reads this column instead of QGIS-internal feature IDs on commit. In order to force QGIS to create a new primary key instead of using the old one (which has been duplicated together with the feature), I simply clear the attribute:
layer = iface.activeLayer()
layer.startEditing()
sourcefeat = next(layer.getFeatures()) # choose the very first feature, for instance
newfeat = QgsFeature()
newfeat.setGeometry(sourcefeat.geometry())
newfeat.setAttributes(sourcefeat.attributes())
idx = layer.fields().indexFromName("fid")
if idx is not None: # check if there is an "fid" attribute
newfeat[idx] = None # clear attribute
layer.addFeature(newfeat)
layer.commitChanges()
-
1I had the same issue when I was copying attributes from one feature to another. attr = node.attributes() then point.setAttributes(attr) I had to make sure I set the 'fid" to None. Thanks!Cary H– Cary H2022年05月31日 15:51:10 +00:00Commented May 31, 2022 at 15:51