How to find that record is new in py file?

How to find that record is new in py file?

Use after_insert hook in your app’s hooks.py file to point to the code you want to execute on new records. This is more suitable for the standard DocTypes that come with ERPNext. In this example the app is called “topcab” and the DocType used is “Cab Request”.

topcab/topcab/hooks.py

doc_events = {
    "Cab Request": {
        "after_insert": "topcab.schedule_cab",
    }
}

topcab/topcab/__init__.py

def schedule_cab(doc, event):
    # executed on new records
    pass

Alternatively, a method named after_insert in the DocType class. This is more suitable for DocTypes you created yourself.

topcab/topcab/topcab/doctype/cab_request/cab_request.py

class CabRequest(Document):

    def after_insert(self):
        # executed on new records
        pass

If I understand the question correctly you can use:

# In this example self is your document
# Returns the Document name if it exists, or nothing if it doesn't
frappe.db.exists('Whatever Doctype', self.name) 
# Returns 1 if the document is new
self.is_new() 

I personally recommend frappe.db.exists since is_new() can lead to different results depending on how the document is created.

1 Like

Its working, thanks!

1 Like