QGIS – Creating QgsFeature with Default Attributes Using PyQGIS

default valuefields-attributespostgispyqgisqgis

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?

Best Answer

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

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