Frappe check if doc exists

I want to insert a doc for my custom DocType on submission and cancel of a “Sales Order” and couldn’t find a function like “frappe.insert_if_not_exists” or similar.
So I catch the exception “frappe.DoesNotExistError” thrown on frappe.get_doc().
And everytime a message pops up with “[docname] not found” but then creates it, because I’m catching the error.
But I don’t want the message box to pop up.
How could I prevent this?

Or am I doing things wrong entirely and there is a function that I couldn’t find that does just that?

Here is my code:

def update_reserved_qty(self, method):
    for item in self.items:

        if item.batch_no:

                br = frappe.get_doc('Batch Reservation', "%s - %s" % (item.batch_no,
            except frappe.DoesNotExistError:
                frappe.msgprint("Creating Doc cuz not exist")
                br = frappe.get_doc({
                    'doctype': 'Batch Reservation',
                    'ref_doctype': self.doctype,
                    'batch_no': item.batch_no,

            reserved_qty = br.db_get('reserved_qty')

            if method == 'on_submit':
                reserved_qty += item.qty
            elif method == 'on_cancel':
                reserved_qty -= item.qty

            br.db_set('reserved_qty', reserved_qty)

You could try something like

if not frappe.db.exists(“Doc Type”, docname):


Instead do:

      if not frappe.db.exists('Batch Reservation', "%s - %s" % (item.batch_no,
          br = frappe.get_doc({
1 Like

From your suggestions I created my own get_doc function that creates the doc if it doesn’t exist.

def get_doc(doctype, args):
    Returns the document requested or creates and inserts it if it doesn't exist

    :param doctype: The doc's doctype
    :param args:    Dictionary of the doc's fields to use if the doc doesn't exist
    :type doctype:  str
    :type args:     dict
    :return:        The document
    :rtype:         frappe.model.document.Document

    if not frappe.db.exists(doctype, args['name']):
        args = dict([('doctype', doctype)] + args.items())
        doc = frappe.get_doc(args)
        return doc

    return frappe.get_doc(doctype, args['name'])

PS: How do I format this properly?
PPS: Thank you, @alec_ruizramon1!

1 Like

@codeag if you use 3x ` at the top and bottom of the code block, it’ll format it as one block. :slight_smile:

1 Like

This topic was automatically closed after 24 hours. New replies are no longer allowed.