feat: set a non-null value if docfield isn't set as nullable

Signed-off-by: Akhil Narang <me@akhilnarang.dev>
This commit is contained in:
Akhil Narang 2023-10-18 13:28:21 +05:30
parent 18867b273f
commit 75709eede7
No known key found for this signature in database
GPG key ID: 9DCC61E211BF645F
2 changed files with 55 additions and 0 deletions

View file

@ -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

50
frappe/utils/defaults.py Normal file
View file

@ -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