After reading @underdark's answer to this question on creating a new vector layer and @Matthias Kuhn's to this one on field calculation, I wrote a script that allows me to calcultate the mean arrival-on-scene time for emergency response services per cell of a grid, even thought some of my values are null.

Steps :

  1. Add attributes in which to calculate mean
  2. Sum the average times of arrival per year (I'm working on 5 years)
  3. Get the number of years for which value is not null
  4. Divide sum by number of not-null-values

My problem is as follows :

The script works fine on OGR layers, but not on Postgres layers. I don't get any errors, but nothing happens when I try to add fields, which is my first step. So right now I have to save my postgres layer as a .shp on my computer to do the treatments I want. Which therefore don't automatically get saved in my database...

Here is the beginning of my script (the part that creates new attributes) :

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

# supply path toqgis
QgsApplication.setPrefixPath("C:\Program Files (x86)\QGIS Wien", True)

# load provider

# set active layer
clayer = qgis.utils.iface.activeLayer()
provider = clayer.dataProvider()

# start editing mode

# add new fields
caps = provider.capabilities()

if caps & QgsVectorDataProvider.AddAttributes:
    res = provider.addAttributes([QgsField("quotient", QVariant.Int), QgsField("moy", QVariant.Int)])


Is there a code line to indicate I want/have rights to alter my postgres layer ?

The most similar questions I could find - this one and this one - didn't get a solution.

I should say I am new to PyQgis so if you are so kind as to answer please explain your suggestion as clearly as possible.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.