6

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 Answers 3

5

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

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

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.

2

Here's an updated example based on Mattias Kuhn's recommendation above, using QGIS 3.22.3 and PostgreSQL 14/PostGIS 3.2:

# Load layer from project and enable editing to add features:
example_layer = QgsProject.instance().mapLayersByName('example_layer')
example_layer.startEditing()

# Row form is (serial, varchar, int, timestamp default current_date)
# Set values to pass onto database in dict via 0-based column indexing:
attributes = {1: 'Example Name', 2: 42} # Columns 1 and 4 auto-generated

# This method handles defaults in the data provider:
feature = QgsVectorLayerUtils.createFeature(example_layer, attributes=attributes)

# The feature is now populated and ready to be submitted and saved:
example_layer.addFeature(feature)
example_layer.commitChanges()

Works just as expected in PyQGIS code.

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.