Deleting Records by removing its reference in link fields

hi all,

I want to delete a record. is there any way to delete the record by removing its reference in link fields(it can be in any doctype)?. I mean is there any inbuild method for it?

Possible. please check the scenario and script.

Whenever a record from Doctype A is deleted, the script will also delete or cancel the linked records in Doctype B.

import frappe

def on_trash(doc, method):
    # Assuming Doctype B has a link field that links to Doctype A
    # Example: fieldname is 'doctype_a_reference'
    linked_docs = frappe.get_all('Doctype B', filters={'doctype_a_reference': doc.name})
    
    for linked_doc in linked_docs:
        try:
            # Delete or cancel the linked document
            linked_doc_doc = frappe.get_doc('Doctype B', linked_doc.name)
            
            # Check if the document can be cancelled or deleted
            if linked_doc_doc.docstatus == 1:
                linked_doc_doc.cancel()
            else:
                linked_doc_doc.delete()
        except Exception as e:
            frappe.log_error(f"Failed to delete/cancel linked document {linked_doc.name} due to {str(e)}", "Linked Document Deletion Error")

Please set your logic in the script and set it according to the scenario.

I hope this helps.