Programmatically Alter the 'name' field of a DocType Record

Hey ppl,

I am trying to change the value of the ‘name’ field for the Account DocType (see why Programmatically Warehouse Creation Missing Ref)

check the following patch…

def execute():
    frappe.reload_doctype('Account')
    accounts = frappe.get_all('Account')
    for account in accounts:
        name_split = account.name.split()
        for addr in ['DE', 'RO']:
            count = Counter(name_split)  # from collections import Counter
            if count[addr] >= 2:
                   # Here I have the desired doc ex INCOMING - DE - DE ---> INCOMING - DE
              
                   # with doc.save:
                   doc = frappe.get_doc('Account', account['name'])
                   doc.name = account[:-5]
                   doc.save(ingnore_permissions=True)
                   #  BREAKS :( , record_name dont exist

                   # with Sql statement 2:
                       frappe.db.sql("""
            		update `tabAccount`
            		set `name` = {0}
            		where `name` = {1}
            	    """.format(account['name'][:-5],  account['name']))
                       # Breaks : (
                       # with db.set_value
                       frappe.db.set_value('Account', account['name'], 'name', str(account[:-5]), modified=True)
                       # TypeError: unhashable type       

I am out of any ideas …

Some more insights from frappe.db.set_value its even strange

old_name= SOMETHING - DE - DE
new_name= SOMETHING - DE

check the where statement!!!

Feeders - RO - RO ---------- Feeders - RO
--- query explain ---
[
 {
  "rows": 1,
  "select_type": "SIMPLE",
  "Extra": "Using where",
  "ref": null,
  "key_len": "562",
  "possible_keys": "PRIMARY",
  "key": "PRIMARY",
  "table": "tabAccount",
  "type": "range",
  "id": 1
 }
]
--- query explain end ---
update `tabAccount`
				set `modified_by`=Administrator, `modified`=True, `name`=Feeders - RO where `name` = Feeders - RO

try

from frappe.model.rename_doc import rename_doc
rename_doc(“Batch”, doc.name, new_name, True, False, True)

@johnskywalker I have tried this one… I will give it a try once more… but I think this one is for DocType renaming… not record field ‘name’ .
Anyway ty

@johnskywalker No luck :frowning:

@johnskywalker I take it back!!!

rename_doc(“Batch”, doc.name, new_name, True, False, True) , I was using merge flag =True.

My fulll patch for others to get the idea:

def execute():
    frappe.reload_doctype('Account')
    accounts = frappe.get_all('Account')
    for account in accounts:
        name_split = account.name.split()
        for addr in ['DE', 'RO']:
            count = Counter(name_split)
            if count[addr] >= 2:
                account_doc = frappe.get_doc('Account', account['name'])
                rename_doc('Account', account_doc.name, account.name[:-10],
                           True, False, True)
                frappe.db.commit()

1 Like