Inside on_update(), How to get the actual DB values using Database APIs?

Hello community members,

I am trying to retrieve the actual database values within the on_update method.

Expectation When I select specific records from the list view and navigate to the edit page, I make changes to a few fields. I want to compare the newly entered values with the existing database values inside the on_update method on save button click. I write get_doc method and try to get the actual DB value

Result To my surprise, both get_list and get_doc merge the results with the form values and return them, meaning the result contains the form values rather than the actual database values for the specific record. However, the database hasn’t been updated yet. I simple couldt get the actual DB values inside the on_update mehtod but I can get the actual DB values on seperate bench console while having debug set on this line

def on_update(self):
        print(' ************* on_update ***************')
        get_fields = ['name', 'branch_id', 'category', 'item', 'standard_stock', 'price']
        result_list = frappe.db.get_list('Asset Master',
                                         filters={},
                                         fields=get_fields)
        # return DB values with the form value merged for this specific record
        print(result_list)

        res_doc = frappe.get_doc('Asset Master', '13')
        # return DB values with the form value merged for this specific record
        print(res_doc.name, res_doc.price)
        

Any changes I make to the fields are reflected when calling get_list and get_doc.
What might be wrong with my approach? I would greatly appreciate any assistance.

If you want to perform validation, use the validate method instead of the on_update method.

1 Like

@thinkdigital

The 'on_update' controller method is always called after the SQL database has experienced an INSERT/UPDATE statement.

(although the SQL transaction may, or may not, be commited yet)

At this point in the flow, the value of"self" will always have the new DocField values.

However, you can get the original, pre-update Document using a built-in method named 'get_doc_before_save()'

For example:

def on_update(self):
    
    # This is the value of a Docfield in the Document, after the update.
    # This value "might" already be committed to SQL, but probably not yet.
    print(self.full_name)

    # To find the value of the same DocField prior to the update, do this:
    my_original_doc = self.get_doc_before_save()
    print(my_original_doc.full_name)
3 Likes