Coverage for apis_core/generic/helpers.py: 84%
81 statements
« prev ^ index » next coverage.py v7.5.3, created at 2025-10-10 13:36 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2025-10-10 13:36 +0000
1import functools
2import logging
4from django.conf import settings
5from django.contrib.auth import get_permission_codename
6from django.db.models import CharField, Model, Q, TextField
7from django.utils import module_loading
9logger = logging.getLogger(__name__)
12def default_search_fields(model, field_names=None):
13 """
14 Retrieve the default model fields to use for a search operation
15 By default those are all the CharFields and TextFields of a model.
16 It is also possible to define those fields on the model using the
17 `_default_search_fields` attribute.
18 The method also takes a `field_names` argument to override the list
19 of fields.
20 """
21 default_types = (CharField, TextField)
22 fields = [
23 field for field in model._meta.get_fields() if isinstance(field, default_types)
24 ]
25 # check if the model has a `_default_search_fields`
26 # list and use that as searchfields
27 if isinstance(getattr(model, "_default_search_fields", None), list):
28 fields = [
29 model._meta.get_field(field) for field in model._default_search_fields
30 ]
31 # if `fields_to_search` is a list, use that
32 if isinstance(field_names, list):
33 fields = [model._meta.get_field(field) for field in field_names]
34 return fields
37def generate_search_filter(model, query, fields_to_search=None, prefix=""):
38 """
39 Generate a default search filter that searches for the `query`
40 This helper can be used by autocomplete querysets if nothing
41 fancier is needed.
42 If the `prefix` is set, the field names will be prefixed with that string -
43 this can be useful if you want to use the `generate_search_filter` in a
44 `Q` combined query while searching over multiple models.
45 """
46 if isinstance(query, str):
47 query = query.split()
49 _fields_to_search = [
50 field.name for field in default_search_fields(model, fields_to_search)
51 ]
53 q = Q()
55 for token in query:
56 q &= functools.reduce(
57 lambda acc, field_name: acc
58 | Q(**{f"{prefix}{field_name}__icontains": token}),
59 _fields_to_search,
60 Q(),
61 )
62 return q
65@functools.lru_cache
66def mro_paths(model):
67 """
68 Create a list of MRO classes for a Django model
69 """
70 paths = []
71 if model is not None:
72 for cls in filter(lambda x: x not in Model.mro(), model.mro()):
73 paths.append(tuple([cls.__module__.split(".")[-2], cls.__name__]))
74 paths.append(tuple(cls.__module__.split(".")[:-1] + [cls.__name__]))
75 return [list(path) for path in list(dict.fromkeys(paths))]
78def template_names_via_mro(model, folder="", prefix="", suffix=""):
79 """
80 Use the MRO to generate a list of template names for a model
81 """
82 results = []
83 for path in mro_paths(model):
84 path = path.copy() # copy, so we don't modify the original list
85 if folder:
86 path.insert(len(path) - 1, folder)
87 path[-1] = f"{prefix}{path[-1]}{suffix}"
88 results.append("/".join(path).lower())
89 return results
92@functools.lru_cache
93def permission_fullname(action: str, model: object) -> str:
94 permission_codename = get_permission_codename(action, model._meta)
95 return f"{model._meta.app_label}.{permission_codename}"
98@functools.lru_cache
99def module_paths(model, path: str = "", suffix: str = "") -> list:
100 paths = list(map(lambda x: x[:-1] + [path] + x[-1:], mro_paths(model)))
101 prepends = []
102 for prepend in getattr(settings, "ADDITIONAL_MODULE_LOOKUP_PATHS", []):
103 prepends.extend(
104 list(map(lambda x: prepend.split(".") + [path] + x[-1:], mro_paths(model)))
105 )
106 classes = tuple(".".join(prefix) + suffix for prefix in prepends + paths)
107 return classes
110@functools.lru_cache
111def makeclassprefix(string: str) -> str:
112 string = "".join([c if c.isidentifier() else " " for c in string])
113 string = "".join([word.strip().capitalize() for word in string.split(" ")])
114 return string
117@functools.lru_cache
118def import_string(dotted_path):
119 try:
120 return module_loading.import_string(dotted_path)
121 except (ModuleNotFoundError, ImportError) as e:
122 logger.debug("Could not load %s: %s", dotted_path, e)
123 return False
126@functools.lru_cache
127def first_member_match(dotted_path_list: tuple[str], fallback=None) -> object:
128 logger.debug("Looking for matching class in %s", dotted_path_list)
129 pathgen = map(import_string, dotted_path_list)
130 result = next(filter(bool, pathgen), None)
131 if result:
132 logger.debug("Found matching attribute/class in %s", result)
133 else:
134 logger.debug("Found nothing, returning fallback: %s", fallback)
135 return result or fallback
138def split_and_strip_parameter(params: [str]) -> [str]:
139 """
140 Clean a URI param list type
141 This method iterates through a list of strings. It looks if
142 the items contain a comma separated list of items and then splits
143 those and also runs strip on all those items.
144 So out of ["foo.bar", "bar.faz, faz.foo"] it
145 creates a list ["foo.bar", "bar.faz", "faz.foo"]
146 """
147 newlist = []
148 for param in params:
149 subparams = map(str.strip, param.split(","))
150 newlist.extend(subparams)
151 return newlist
154def string_to_bool(string: str = "false") -> bool:
155 """
156 Convert a string to a boolean representing its semantic value
157 """
158 return string.lower() == "true"