From 7c0078d8e44af234a3cf9f5948f6d26586d4be2c Mon Sep 17 00:00:00 2001 From: Raffael Meyer <14891507+barredterra@users.noreply.github.com> Date: Wed, 17 Nov 2021 05:32:11 +0100 Subject: [PATCH] feat: Convenience methods for NestedSet {get_parent, get_children} (#13579) * feat: new properties `NestedSet.{parent, children}` * fix: typo * refactor: remove unused kwargs * feat: method instead of property * feat: use generator * docs: fix docstring to match modified method * refactor: add type hints * refactor: type hints as string for compatibility with python <3.7 https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class * refactor: import Iterator for type annotation * refactor: Apply suggestions from code review Co-authored-by: gavin Co-authored-by: gavin --- frappe/utils/nestedset.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/frappe/utils/nestedset.py b/frappe/utils/nestedset.py index 4d9472dabb..5c4beda71e 100644 --- a/frappe/utils/nestedset.py +++ b/frappe/utils/nestedset.py @@ -10,6 +10,8 @@ # 3. call update_nsm(doc_obj) in the on_upate method # ------------------------------------------ +from typing import Iterator + import frappe from frappe import _ from frappe.model.document import Document @@ -271,6 +273,19 @@ class NestedSet(Document): def get_ancestors(self): return get_ancestors_of(self.doctype, self.name) + def get_parent(self) -> "NestedSet": + """Return the parent Document.""" + parent_name = self.get(self.nsm_parent_field) + if parent_name: + return frappe.get_doc(self.doctype, parent_name) + + def get_children(self) -> Iterator["NestedSet"]: + """Return a generator that yields child Documents.""" + child_names = frappe.get_list(self.doctype, filters={self.nsm_parent_field: self.name}, pluck="name") + for name in child_names: + yield frappe.get_doc(self.doctype, name) + + def get_root_of(doctype): """Get root element of a DocType with a tree structure""" result = frappe.db.sql("""select t1.name from `tab{0}` t1 where