Update doctype using a dictionary

Hello, is there a way to update a doctype using a dictionary?

if frappe.db.exists('Birthday', {'user': user}):
    bday = frappe.get_doc('Birthday', new_data_dict)
    bday.save()

Instead of doing this:

# data is my dict with updated fields
data = {}

if frappe.db.exists('Birthday', {'user': user}):
    bday = frappe.get_doc('Birthday', {'user': user})
    bday.date = data["date"]
    bday.location = data["location"]
    bday.surprise = data["surprise"]
    bday.save()
else:
    bday = frappe.get_doc('Birthday', data)
    bday.insert()

Thanks

Hi @JPaulMora,

Please check the syntax and try it.

data = {
    "date": "2023-09-15",
    "location": "Gandhinagar",
    "Gift": "iPhone 14"
}

user = "ncp@erp.com"

if frappe.db.exists('Birthday', {'user': user}):
    bday = frappe.get_doc('Birthday', {'user': user})
    for field, value in data.items():
        frappe.set_value('Birthday', bday.name, field, value)
    bday.save()
else:
    data['user'] = user
    bday = frappe.get_doc(data)
    bday.insert()

Thank You!

1 Like