From 75709eede7a9eab88b0668dc20bca97564f6b2e3 Mon Sep 17 00:00:00 2001 From: Akhil Narang Date: Wed, 18 Oct 2023 13:28:21 +0530 Subject: [PATCH] feat: set a non-null value if docfield isn't set as nullable Signed-off-by: Akhil Narang --- frappe/model/base_document.py | 5 ++++ frappe/utils/defaults.py | 50 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 frappe/utils/defaults.py diff --git a/frappe/model/base_document.py b/frappe/model/base_document.py index 78c20a2eae..264ec219b3 100644 --- a/frappe/model/base_document.py +++ b/frappe/model/base_document.py @@ -31,6 +31,7 @@ from frappe.utils import ( sanitize_html, strip_html, ) +from frappe.utils.defaults import get_not_null_defaults from frappe.utils.html_utils import unescape_html if TYPE_CHECKING: @@ -384,6 +385,10 @@ class BaseDocument: if ignore_nulls and not is_virtual_field and value is None: continue + # If the docfield is not nullable - set a default non-null value + if value is None and getattr(df, "not_nullable", False): + value = get_not_null_defaults(df.fieldtype) + d[fieldname] = value return d diff --git a/frappe/utils/defaults.py b/frappe/utils/defaults.py new file mode 100644 index 0000000000..152efef8e3 --- /dev/null +++ b/frappe/utils/defaults.py @@ -0,0 +1,50 @@ +from typing import Literal + + +def get_not_null_defaults(column_type: str) -> Literal["", 0] | None: + """ + Method to return a default value for a column type that is not NoneType + :param column_type: The type of column + :return: The value to be set + """ + column_type_map = { + "Data": str, + "Text": str, + "Autocomplete": str, + "Attach": str, + "AttachImage": str, + "Barcode": str, + "Check": int, + "Code": str, + "Color": str, + "Currency": float, + "Date": str, + "Datetime": str, + "Duration": int, + "DynamicLink": str, + "Float": float, + "HTMLEditor": str, + "Int": int, + "JSON": str, + "Link": str, + "LongText": str, + "MarkdownEditor": str, + "Password": str, + "Percent": float, + "Phone": str, + "ReadOnly": str, + "Rating": float, + "Select": str, + "SmallText": str, + "TextEditor": str, + "Time": str, + "Table": list, + "Table MultiSelect": list, + } + data_type = column_type_map.get(column_type.replace(" ", ""), str) + # data_type = eval(f"frappe.types.DF.{column_type.replace(' ', '')}") + if data_type == str: + return "" + if data_type in (int, float): + return 0 + return None