tidy up casting

This commit is contained in:
Aaron Kable
2026-01-08 21:03:45 +08:00
parent e44802fa73
commit a01598e088

View File

@@ -15,15 +15,31 @@ logger = get_extension_logger(__name__)
class nested_param_dict(dict): class nested_param_dict(dict):
"""
Helper to create infinite depth default dicts for setting from params
"""
def __setitem__(self, item, value): def __setitem__(self, item, value):
if "." in item: if "." in item:
head, path = item.split(".", 1) head, path = item.split(".", 1)
try:
head = int(head)
except ValueError:
pass
obj = self.setdefault(head, nested_param_dict()) obj = self.setdefault(head, nested_param_dict())
obj[path] = value obj[path] = value
else: else:
super().__setitem__(item, value) super().__setitem__(item, value)
def defaultdict_to_dict(d):
"""
Helper to convert default dict back to dict
"""
if isinstance(d, defaultdict):
d = {k: defaultdict_to_dict(v) for k, v in d.items()}
return d
class DataTablesView(View): class DataTablesView(View):
model: Model = None model: Model = None
@@ -38,27 +54,37 @@ class DataTablesView(View):
for id, c in table_conf["columns"].items(): for id, c in table_conf["columns"].items():
_c = self.columns[int(id)][0] _c = self.columns[int(id)][0]
if c["searchable"] and len(_c) > 0: if c["searchable"] and len(_c) > 0:
if len(c["search"]["value"]) and len(_c): _sv = str(c["search"]["value"])
if len(_sv) > 0:
if c["search"]["regex"]: if c["search"]["regex"]:
filter_qs |= Q(**{f'{_c}__iregex': c["search"]["value"]}) filter_qs |= Q(**{f'{_c}__iregex': _sv})
else: else:
filter_qs |= Q(**{f'{_c}__icontains': c["search"]["value"]}) filter_qs |= Q(**{f'{_c}__icontains': _sv})
if len(table_conf["search"]["value"]) > 0: _gsv = str(table_conf["search"]["value"])
filter_qs |= Q(**{f'{_c}__icontains': table_conf["search"]["value"]}) if len(_gsv) > 0:
filter_qs |= Q(**{f'{_c}__icontains': _gsv})
return filter_qs return filter_qs
def get_table_config(self, get: dict): def get_table_config(self, get: dict):
_cols = nested_param_dict() _cols = nested_param_dict()
for c, v in get.items(): for c, v in get.items():
_keys = [_k for _k in c.replace("]", "").split("[")] _keys = [_k for _k in c.replace("]", "").split("[")]
_cols[".".join(_keys)] = v _v = v
return _cols if v in ["true", "false"]:
_v = _v == "true"
else:
try:
_v = int(_v)
except ValueError:
pass # not an integer
_cols[".".join(_keys)] = _v
return defaultdict_to_dict(_cols)
def get_order(self, table_conf: dict): def get_order(self, table_conf: dict):
order = [] order = []
for oc, od in table_conf["order"].items(): for oc, od in table_conf["order"].items():
_c = table_conf["columns"][od["column"]] _c = table_conf["columns"][od["column"]]
if _c["orderable"] == "true": if _c["orderable"]:
if od["dir"] == "desc": if od["dir"] == "desc":
order.append("-" + self.columns[int(od["column"])][0]) order.append("-" + self.columns[int(od["column"])][0])
else: else: