3

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
2

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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