feat: frappe.utils.data.cast

Cast the value to the Python native object of the Frappe fieldtype provided. If value is None, the first/lowest value of the `fieldtype` will be returned.

Mapping of Python types => Frappe types:
* float => ("Currency", "Float", "Percent")
* int => ("Int", "Check")
* datetime.datetime => ("Datetime",)
* datetime.date => ("Date",)
* datetime.time => ("Time",)

Deprecate frappe.utils.data.cast_fieldtype in favour of new util cast
which handles types "better"
This commit is contained in:
Gavin D'souza 2021-08-20 12:35:24 +05:30
parent cb034e4c52
commit a2cb9be7a4

View file

@ -8,6 +8,7 @@ import re, datetime, math, time
from code import compile_command
from urllib.parse import quote, urljoin
from frappe.desk.utils import slug
from click import secho
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S.%f"
@ -505,7 +506,36 @@ def has_common(l1, l2):
"""Returns truthy value if there are common elements in lists l1 and l2"""
return set(l1) & set(l2)
def cast_fieldtype(fieldtype, value=None):
def cast_fieldtype(fieldtype, value):
# TODO: Add DeprecationWarning for this util
message = (
"Function `frappe.utils.data.cast` has been deprecated in favour"
" of `frappe.utils.data.cast`. Use the newer util for safer type casting. "
)
secho(message, fg="yellow")
if fieldtype in ("Currency", "Float", "Percent"):
value = flt(value)
elif fieldtype in ("Int", "Check"):
value = cint(value)
elif fieldtype in ("Data", "Text", "Small Text", "Long Text",
"Text Editor", "Select", "Link", "Dynamic Link"):
value = cstr(value)
elif fieldtype == "Date":
value = getdate(value)
elif fieldtype == "Datetime":
value = get_datetime(value)
elif fieldtype == "Time":
value = to_timedelta(value)
return value
def cast(fieldtype, value=None):
"""Cast the value to the Python native object of the Frappe fieldtype provided.
If value is None, the first/lowest value of the `fieldtype` will be returned.
@ -1218,7 +1248,7 @@ def evaluate_filters(doc, filters):
def compare(val1, condition, val2, fieldtype=None):
ret = False
if fieldtype:
val2 = cast_fieldtype(fieldtype, val2)
val2 = cast(fieldtype, val2)
if condition in operator_map:
ret = operator_map[condition](val1, val2)