13

When I try to calculate a new field with:

idx = layer.fieldNameIndex(attributeName)

I receive the following error:

AttributeError: 'QgsVectorLayer' object has no attribute 'fieldNameIndex'

What´s the problem? I'm using QGIS 3.0.1 64x in Windows.

Taras
  • 32,823
  • 4
  • 66
  • 137
Novvier
  • 446
  • 3
  • 13

2 Answers2

19

In PyQGIS 3

Use one of the following methods from the QgsFields class:

  1. indexFromName()

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.indexFromName("FIELD_NAME")
    
  2. lookupField():

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.lookupField("FIELD_NAME")
    
  3. indexOf()

    layer = iface.activeLayer()
    layer_fields = layer.fields()
    field_index = layer_fields.indexOf("FIELD_NAME")
    
Taras
  • 32,823
  • 4
  • 66
  • 137
user122730
  • 206
  • 2
  • 3
7

You need to access it via the fieldNameIndex() method of the QgsVectorDataProvider class:

layer = iface.activeLayer()
idx = layer.dataProvider().fieldNameIndex(attributeName)
Taras
  • 32,823
  • 4
  • 66
  • 137
Joseph
  • 75,746
  • 7
  • 171
  • 282