[Qgis-developer] Problem with addAttribute and Postgres default value

Luca Manganelli luca76 at gmail.com
Wed Apr 22 23:25:08 PDT 2015


On Wed, Apr 22, 2015 at 4:15 PM, Luca Manganelli <luca76 at gmail.com> wrote:
> Hi,
>
> I have a spatial table with an attribute that uses the today's date as
> a default value.

I found myself the solution to the problem.
The trick is to check if the defaultValue() of the field is not null:

# Create new feature
new_feature = QgsFeature()
new_feature.initAttributes ( len ( layer.dataProvider().fieldNameMap() ) )
new_feature.setGeometry( ... )

# Populate fields with DEFAULT value in Postgres
new_attributes = layer.pendingFields()
for j in new_attributes:
  fieldname = j.name()
  fieldindex = layer.dataProvider().fieldNameIndex(fieldname)
  fielddefault = layer.dataProvider().defaultValue(fieldindex)

  if fieldindex == 0:  # skip ogc_fid (mine is at index 0)
    continue

  if unicode (fielddefault) != "NULL":
    new_feature.setAttribute (fieldindex, fielddefault)

# Populate your fields
new_feature.setAttribute ( ..., ... )


More information about the Qgis-developer mailing list