3

I would like to delete all fields with the string "RAWI". For instance the field "RAWI_WA" and the field "RAWI_BO" should be deleted but not the field "NSG_RAW"

Joseph
  • 75,746
  • 7
  • 171
  • 282
klausk
  • 333
  • 3
  • 9

1 Answers1

6

You can use the following code in the Python console which, for your selected layer, deletes all fields which contains RAWI in the field name:

layer = qgis.utils.iface.activeLayer()
# Get field names of layer
field_names = [field.name() for field in layer.fields()]

# Use `with edit()` method to edit and commit changes in one go
with edit(layer):
    # Assign count in reverse order for each field which will be used as index
    for i, j in reversed(list(enumerate(field_names))):
        if "RAWI" in j:
            layer.deleteAttribute(i)
Joseph
  • 75,746
  • 7
  • 171
  • 282
  • 2
    Lovely use of enumerate to get the index and item. – Richard Morgan Mar 30 '16 at 12:46
  • @RichardMorgan - Thank you :) I'm sure there's a nicer way of getting the indices for the relevant fields! – Joseph Mar 30 '16 at 12:49
  • 2
    layer.startEdiging() and layer.commitChanges() do nothing if the nested calls are on the dataprovider. rather use layer.deleteAttribute(idx) instead. And if you want to have it extra-nice you can use with edit(layer) instead :) (reference: http://www.opengis.ch/2015/08/12/with-edit-layer/) – Matthias Kuhn Apr 01 '16 at 07:23
  • @MatthiasKuhn - Thank you =). I've used the with edit(layer): method as you suggested, however I seem to be having issues with layer.deleteAttribute(). If I put this inside the if loop, it only deletes half of the fields each time the code is run. Guess I missed something... ;) – Joseph Apr 01 '16 at 10:25
  • 2
    That's probably caused by the indexes changing while removing fields. Better iterate in reverse order. And still, if using startEditing() or with edit don't use dataProvider() at all - or skip the startEditing() / with edit part ;) – Matthias Kuhn Apr 01 '16 at 10:29
  • @MatthiasKuhn - Ahh you're a genius! Many thanks for your valuable lesson :) – Joseph Apr 01 '16 at 10:42
  • 2
    One last hint: use layer.fields() (or for older qgis versions layer.pendingFields()) or you may have troubles with joined and virtual fields. – Matthias Kuhn Apr 01 '16 at 10:49
  • I tried the with edit(layer): in the console and it worked great. It does not seem to work in a plugin. Does anyone know what is missing for the plugin? – Cary H Apr 02 '20 at 13:36