diff --git a/frappe/model/document.py b/frappe/model/document.py index b582b7f3ae..72050cad5c 100644 --- a/frappe/model/document.py +++ b/frappe/model/document.py @@ -301,12 +301,16 @@ class Document(BaseDocument): return if rows: - # delete rows that do not match the ones in the - # document - frappe.db.sql("""delete from `tab{0}` where parent=%s + # select rows that do not match the ones in the document + deleted_rows = frappe.db.sql("""select name from `tab{0}` where parent=%s and parenttype=%s and parentfield=%s and name not in ({1})""".format(df.options, ','.join(['%s'] * len(rows))), [self.name, self.doctype, fieldname] + rows) + if len(deleted_rows) > 0: + # delete rows that do not match the ones in the document + frappe.db.sql("""delete from `tab{0}` where name in ({1})""".format(df.options, + ','.join(['%s'] * len(deleted_rows))), tuple(row[0] for row in deleted_rows)) + else: # no rows found, delete all rows frappe.db.sql("""delete from `tab{0}` where parent=%s