5

I'm having trouble adding a field to a PostGIS table using PyQGIS. Here's my code:

from PyQt4.QtCore import QVariant
from qgis.core import *

inLayer = iface.activeLayer()
provider = inLayer.dataProvider()

# add field
field = QgsField('test_field', QVariant.String)
inLayer.startEditing()
provider.addAttributes([field])
inLayer.updateFields()

# commit
inLayer.commitChanges()

The commit fails and the PostGIS log shows an error:

2015-10-27T08:13:28 1 Erroneous query: ALTER TABLE "received"."env" ADD COLUMN "test_field" returned 7 [ERROR: syntax error at end of input

LINE 1: ALTER TABLE "received"."env" ADD COLUMN "test_field"

Seems the call to PostGIS fails to include the column type. Is this a bug, or am I going about this the wrong way?

1

If you need to add a new column in your layer from Postgis, use this:

layer = iface.activeLayer()

name_column = "new_column"

layer.dataProvider().addAttributes([QgsField(name_column, QVariant.String, "VARCHAR")])
layer.updateFields()
2
  • Please avoid duplicate answers: gis.stackexchange.com/a/326197/8104
    – Aaron
    Jun 19 '19 at 2:16
  • @bugmenot123 The duplicate answer that I linked was deleted. Are you referring to the accepted answer in the linked thread?
    – Aaron
    Jun 17 at 9:54

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.