5

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"

0

1 Answer 1

3

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()
1
  • 1
    I 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
    May 31, 2022 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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