I wrote a function that is supposed to delete all fields of a layer except a required one.

My idea was to iterate over all fields of the layer and save all fieldnames except the required one in a List.

NextI want to execute the tool qgis:deletecolumn and pass the list as fields to drop. I'm using QGIS 3.4 that's why I chose 'qgis:deletecolumn' and not "qgis:dropfields'.

This is the code:

def Channel2(self):
    channel1 = self.Channel1()
    fieldname = self.dlg.Channel_ID.currentText()
    fieldNameList = []
    for field in channel1.fields():
        if not (field.name == fieldname):
    param = {'INPUT': channel1,
             'COLUMN': fieldNameList,
             'OUTPUT': 'memory:'}
    channel2 = processing.run('qgis:deletecolumn', param)
    vlayer = channel2['OUTPUT']
    return vlayer

I don't get any error message and I do get a new layer as output but the new layer still has all the fields. Checking the documentation it seems that I don't pass a list to the Parameter 'COLUMN' but a "tablefield". But I don't know find what a "tablefield" is supposed to be and how to create it. Or is the error somewhere else?

  • 1
    Ahhh ok I see. Now it works. Thanks again @BERA! – DGIS Apr 30 at 8:53

field.name is a method, you need to call it with (): field.name() is the field name.

Same as:

somelist = ['a','b']
[letter.upper for letter in somelist]
[<built-in method upper of str object at 0x000002CDB16DCDF8>, <built-in method upper of str object at 0x000002CDB16DC768>]

[letter.upper() for letter in somelist]
['A', 'B']

So your fieldnamelist is a list of methods, not fieldnames. Try:

if field.name() != fieldname:
| improve this answer | |

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.