2

I'm looking for a solution to rename a field/attribute via dataprovider (see the code below):

def modifierChamp(self,file_table,nom_champ,nom_champ_new):
    #vérifie que le champ existe
    dp = file_table.dataProvider()
    ind = dp.fieldNameIndex(nom_champ)
    if ind==-1:
        self.logFile.write("Le champ "+nom_champ+u" Nexiste PAS dans la table "+file_table.name()+" \n")
    else:
        # renameAttributes exists but I don't find how to use it !
        dp.renameAttributes(QgsFieldNameMap(ind,nom_champ_new)) # it does not work
        dp.updateFields()
        self.logFile.write("Correction du nom du champ "+nom_champ+" par "+nom_champ_new+" dans la table "+str(file_table.name())+" \n")
2

1 Answer 1

1

Following Python code in official unit tests here, modify your code to :

def modifierChamp(self, file_table, nom_champ, nom_champ_new):
    # Vérifie que le champ existe
    dp = file_table.dataProvider()
    ind = dp.fieldNameIndex(nom_champ)
    if ind==-1:
        self.logFile.write("Le champ " + nom_champ + " n\'existe pas dans la table " + file_table.name() + " \n")
    else:
        dp.renameAttributes({ind: nom_champ_new})
        file_table.updateFields()
        self.logFile.write("Correction du nom du champ " + nom_champ + " par " + nom_champ_new + " dans la table " + str(file_table.name()) + " \n")

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.