Coverage for apis_core/generic/helpers.py: 33%
76 statements
« prev ^ index » next coverage.py v7.5.3, created at 2025-09-03 06:15 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2025-09-03 06:15 +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))]
78@functools.lru_cache
79def template_names_via_mro(model, suffix=""):
80 """
81 Use the MRO to generate a list of template names for a model
82 """
83 mro_prefix_list = ["/".join(prefix) for prefix in mro_paths(model)]
84 return [f"{prefix.lower()}{suffix}" for prefix in mro_prefix_list]
87@functools.lru_cache
88def permission_fullname(action: str, model: object) -> str:
89 permission_codename = get_permission_codename(action, model._meta)
90 return f"{model._meta.app_label}.{permission_codename}"
93@functools.lru_cache
94def module_paths(model, path: str = "", suffix: str = "") -> list:
95 paths = list(map(lambda x: x[:-1] + [path] + x[-1:], mro_paths(model)))
96 prepends = []
97 for prepend in getattr(settings, "ADDITIONAL_MODULE_LOOKUP_PATHS", []):
98 prepends.extend(
99 list(map(lambda x: prepend.split(".") + [path] + x[-1:], mro_paths(model)))
100 )
101 classes = tuple(".".join(prefix) + suffix for prefix in prepends + paths)
102 return classes
105@functools.lru_cache
106def makeclassprefix(string: str) -> str:
107 string = "".join([c if c.isidentifier() else " " for c in string])
108 string = "".join([word.strip().capitalize() for word in string.split(" ")])
109 return string
112@functools.lru_cache
113def import_string(dotted_path):
114 try:
115 return module_loading.import_string(dotted_path)
116 except (ModuleNotFoundError, ImportError) as e:
117 logger.debug("Could not load %s: %s", dotted_path, e)
118 return False
121@functools.lru_cache
122def first_member_match(dotted_path_list: tuple[str], fallback=None) -> object:
123 logger.debug("Looking for matching class in %s", dotted_path_list)
124 pathgen = map(import_string, dotted_path_list)
125 result = next(filter(bool, pathgen), None)
126 if result:
127 logger.debug("Found matching attribute/class in %s", result)
128 else:
129 logger.debug("Found nothing, returning fallback: %s", fallback)
130 return result or fallback
133def split_and_strip_parameter(params: [str]) -> [str]:
134 """
135 Clean a URI param list type
136 This method iterates through a list of strings. It looks if
137 the items contain a comma separated list of items and then splits
138 those and also runs strip on all those items.
139 So out of ["foo.bar", "bar.faz, faz.foo"] it
140 creates a list ["foo.bar", "bar.faz", "faz.foo"]
141 """
142 newlist = []
143 for param in params:
144 subparams = map(str.strip, param.split(","))
145 newlist.extend(subparams)
146 return newlist
149def string_to_bool(string: str = "false") -> bool:
150 """
151 Convert a string to a boolean representing its semantic value
152 """
153 return string.lower() == "true"