3

I have a polygon layer loaded from POSTGIS database. This layer has a default value for the first column. I can create a new feature set that attribute to some predefined value with

    newFeature = QgsFeature()
    newFeature.setFields(activeLayer.pendingFields())
    newFeature.setAttribute(0, "someValue")

But I want to set it to the default value that comes from the layer. When I try to add a feature with QGIS 2.10 it automatically sets the default value for that column. How can I achieve that with PyQGIS?

3

Default values are accessible via the data provider, so this may work for simple cases:

provider = activeLayer.dataProvider()
newFeature.setAttribute(0, provider.defaultValue(0))
1

Default values can be provided by both, the data provider and a definition within QGIS.

Starting with QGIS 3, there is a method createFeature in QgsVectorLayerUtils that takes care of resolving default values appropriately and also takes care of unique value constraints and similar pitfalls.

feature = QgsVectorLayerUtils.createFeature(layer)

Sometimes, it's also useful to already have the default value available directly on the form within QGIS before actually having clicked ok on the form. This behavior can be enabled by enabling "evaluate default values server side" in the project properties. So far, this is only implemented for Postgres.

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.