Coverage for apis_core/generic/abc.py: 62%
261 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-23 06:59 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-23 06:59 +0000
1import functools
2import logging
3import re
4from typing import Optional, Tuple
6from django.contrib.contenttypes.models import ContentType
7from django.core.checks import Error
8from django.core.exceptions import ImproperlyConfigured
9from django.db import models
10from django.db.models import BooleanField, CharField, TextField
11from django.db.models.fields.related import ForeignKey, ManyToManyField
12from django.db.models.query import QuerySet
13from django.forms import model_to_dict
14from django.http.request import HttpRequest
15from django.urls import reverse
16from django.utils.encoding import force_str
17from django.utils.translation import gettext_lazy as _
19from apis_core.generic.helpers import mro_paths, permission_fullname
20from apis_core.generic.signals import (
21 post_duplicate,
22 post_merge_with,
23 pre_duplicate,
24 pre_import_from,
25 pre_merge_with,
26)
27from apis_core.generic.utils import get_autocomplete_data_and_normalized_uri
28from apis_core.generic.utils.models import ConfigModel
29from apis_core.utils.settings import apis_base_uri, rdf_namespace_prefix
31logger = logging.getLogger(__name__)
34class GenericModel(models.Model):
35 class Meta:
36 abstract = True
38 class Config:
39 overview_section = _("Generic models")
40 index_for_search = True
41 enable_uris = True
43 @classmethod
44 def check(cls, **kwargs):
45 errors = super().check(**kwargs)
46 msgs = ConfigModel.validation_errors_to_error_messages(cls.Config)
47 errors.extend([Error(msg, obj=cls) for msg in msgs])
48 return errors
50 def __repr__(self):
51 if id := getattr(self, "id", None):
52 return super().__repr__() + f" (ID: {id})"
53 return super().__repr__()
55 @property
56 def get_self_content_type(self):
57 return ContentType.objects.get_for_model(self)
59 @classmethod
60 def get_listview_url(cls):
61 return reverse("apis_core:generic:list", args=[cls])
63 @classmethod
64 def get_createview_url(cls):
65 return reverse("apis_core:generic:create", args=[cls])
67 @classmethod
68 def get_importview_url(cls):
69 return reverse("apis_core:generic:import", args=[cls])
71 @classmethod
72 def get_openapi_tags(cls):
73 return [item[-1] for item in mro_paths(cls)]
75 @classmethod
76 def get_namespace_prefix(cls):
77 ct = ContentType.objects.get_for_model(cls)
78 return f"{rdf_namespace_prefix()}-{ct.model}"
80 @classmethod
81 def get_namespace_uri(cls):
82 return apis_base_uri() + cls.get_listview_url()
84 @classmethod
85 def get_rdf_types(cls):
86 return []
88 @classmethod
89 def get_count(cls):
90 return cls.objects.count()
92 def get_edit_url(self):
93 return reverse("apis_core:generic:update", args=[type(self), self.id])
95 def get_duplicate_url(self):
96 return reverse("apis_core:generic:duplicate", args=[type(self), self.id])
98 def get_enrich_url(self):
99 return reverse("apis_core:generic:enrich", args=[type(self), self.id])
101 def get_absolute_url(self):
102 return reverse("apis_core:generic:detail", args=[type(self), self.id])
104 def get_delete_url(self):
105 return reverse("apis_core:generic:delete", args=[type(self), self.id])
107 def get_merge_url(self, other_id):
108 return reverse("apis_core:generic:merge", args=[type(self), self.id, other_id])
110 def get_select_merge_or_enrich_url(self):
111 return reverse(
112 "apis_core:generic:selectmergeorenrich", args=[type(self), self.id]
113 )
115 def get_create_success_url(self, request: Optional[HttpRequest] = None):
116 if request and request.GET.get("redirect", False):
117 return request.GET.get("redirect")
118 return self.get_absolute_url()
120 def get_update_success_url(self, request: Optional[HttpRequest] = None):
121 if request and request.GET.get("redirect", False):
122 return request.GET.get("redirect")
123 return self.get_edit_url()
125 def get_delete_success_url(self, request: Optional[HttpRequest] = None):
126 if request and request.GET.get("redirect", False):
127 return request.GET.get("redirect")
128 return self.get_listview_url()
130 def get_api_detail_endpoint(self):
131 return reverse(
132 "apis_core:generic:genericmodelapi-detail", args=[type(self), self.id]
133 )
135 @classmethod
136 def get_change_permission(self):
137 return permission_fullname("change", self)
139 @classmethod
140 def get_add_permission(self):
141 return permission_fullname("add", self)
143 @classmethod
144 def get_delete_permission(self):
145 return permission_fullname("delete", self)
147 @classmethod
148 def get_view_permission(self):
149 return permission_fullname("view", self)
151 @classmethod
152 def get_verbose_name_plural(cls):
153 return cls._meta.verbose_name_plural
155 @classmethod
156 def get_verbose_name(cls):
157 return cls._meta.verbose_name
159 @classmethod
160 def valid_import_url(cls, uri: str):
161 """
162 Check if an URI is a can be imported.
163 The exact fetching logic for an URI is defined in the
164 `import_definitions` attribute of the class.
165 `import_definitions` has to be a dict, mapping a regex
166 matching the URI to a callable taking the URI as an argument.
167 This method check if there is a callable defined for this URI.
168 """
169 _, uri = get_autocomplete_data_and_normalized_uri(uri)
170 for regex, fn in getattr(cls, "import_definitions", {}).items():
171 if re.match(regex, uri):
172 return fn
173 return False
175 @classmethod
176 def get_data_and_normalized_uri(cls, uri: str) -> Tuple[dict, str]:
177 data, uri = get_autocomplete_data_and_normalized_uri(uri)
178 return data, uri
180 @classmethod
181 @functools.cache
182 def fetch_from(cls, uri: str):
183 """
184 Normalize the URI and extract the autocomplete data.
185 Then try to fetch data from an URI:
186 Check if there is import logic configured for this URI and if
187 so, use that import logic to fetch the data.
188 Finally, combine the fetched data and the autocomplete data.
189 """
190 logger.debug("Fetch from %s", uri)
191 data, nuri = cls.get_data_and_normalized_uri(uri)
192 if fn := cls.valid_import_url(nuri):
193 fetcheddata = fn(nuri) or {}
194 # merge the two dicts
195 ret = fetcheddata | data
196 # combine values that exist in both dicts
197 for key in set(fetcheddata).intersection(data):
198 ret[key] = fetcheddata[key] + data[key]
199 return ret
200 raise ImproperlyConfigured(f"Import not configured for URI {uri}")
202 @classmethod
203 def import_from(cls, uri: str, allow_empty: bool = True):
204 """
205 Fetch data from an URI and create a model instance using
206 that data. If the `allow_empty` argument is set, this also
207 creates a model instance if the data fetched was empty. This
208 might make sense if you still want to create an instance and
209 attach the URI to it.
210 """
211 # we allow other apps to injercept the import
212 # whatever they return will be used instead of
213 # creating a new object
214 _, nuri = cls.get_data_and_normalized_uri(uri)
215 for receiver, response in pre_import_from.send(sender=cls, uri=nuri):
216 if response:
217 return response
218 data = cls.fetch_from(uri) or {}
219 if allow_empty or data:
220 instance = cls()
221 instance.save()
222 instance.import_data(data)
223 return instance
224 raise ValueError(f"Could not fetch data to import from {uri}")
226 def import_from_dict_subset(self, **data):
227 """
228 Import attributes of this instance from data in a dict.
229 We iterate through the individual values of the dict and
230 a) only set them if the instance has an attribute matching
231 the key and b) use the fields `clean` method to check if
232 the value validates. If it does not validate, we return
233 the validation error in the errors dict.
234 """
235 self._import_errors = {}
236 if data:
237 for field in self._meta.fields:
238 if data.get(field.name, False):
239 value = str(data[field.name][0])
240 try:
241 field.clean(value, self)
242 except Exception as e:
243 logger.info(
244 "Could not set %s on %s: %s", field.name, str(self), str(e)
245 )
246 self._import_errors[field.name] = str(e)
247 else:
248 setattr(self, field.name, value)
249 self.save()
251 def import_data(self, data):
252 self.import_from_dict_subset(**data)
254 def get_merge_charfield_value(self, other: CharField, field: CharField):
255 res = getattr(self, str(field.name))
256 if not field.choices:
257 otherres = getattr(other, str(field.name), res)
258 if not res:
259 res = otherres
260 elif otherres and otherres != res:
261 res += f" ({otherres})"
263 return res
265 def get_merge_textfield_value(self, other: TextField, field: TextField):
266 res = getattr(self, str(field.name))
267 if getattr(other, str(field.name)):
268 # if own value is None, fallback to empty string
269 res = res or ""
270 res += "\n" + f"Merged from {other}:\n" + getattr(other, str(field.name))
271 return res
273 def get_merge_booleanfield(self, other: BooleanField, field: BooleanField):
274 return getattr(other, str(field.name))
276 def get_field_value_after_merge(self, other, field):
277 """
278 This method finds the value of a field after merging `other` into `self`.
279 It first tries to find a merge method that is specific to that field
280 (merge_{fieldname}) and then tries to find a method that is specific to
281 the type of the field (merge_{fieldtype})
282 If neither of those exist, it uses the others field value if the field
283 in self is not set, otherwise it keeps the value in self.
284 """
285 fieldtype = field.get_internal_type().lower()
286 # if there is a `get_merge_{fieldname}` method in this model, use that one
287 if callable(getattr(self, f"get_merge_{field.name}_value", None)):
288 return getattr(self, f"get_merge_{field.name}_value")(other)
289 # otherwise we check if there is a method for the field type and use that one
290 elif callable(getattr(self, f"get_merge_{fieldtype}_value", None)):
291 return getattr(self, f"get_merge_{fieldtype}_value")(other, field)
292 else:
293 if not getattr(self, str(field.name)):
294 return getattr(other, str(field.name))
295 return getattr(self, field.name)
297 def merge_fields(self, other):
298 """
299 This method iterates through the model fields and uses the
300 `get_field_value_after_merge` method to copy values from `other` to `self`.
301 It is called by the `merge_with` method.
302 """
303 for field in self._meta.fields:
304 newval = self.get_field_value_after_merge(other, field)
305 if newval != getattr(self, str(field.name)):
306 setattr(self, str(field.name), newval)
307 self.save()
309 def merge_with(self, entities):
310 if self in entities:
311 entities.remove(self)
312 origin = self.__class__
313 pre_merge_with.send(sender=origin, instance=self, entities=entities)
315 e_a = type(self).__name__
316 self_model_class = ContentType.objects.get(model__iexact=e_a).model_class()
317 if isinstance(entities, int):
318 entities = self_model_class.objects.get(pk=entities)
319 if not isinstance(entities, list) and not isinstance(entities, QuerySet):
320 entities = [entities]
321 entities = [
322 self_model_class.objects.get(pk=ent) if isinstance(ent, int) else ent
323 for ent in entities
324 ]
325 for ent in entities:
326 e_b = type(ent).__name__
327 if e_a != e_b:
328 continue
329 for f in ent._meta.local_many_to_many:
330 if not f.name.endswith("_set"):
331 sl = list(getattr(self, f.name).all())
332 for s in getattr(ent, f.name).all():
333 if s not in sl:
334 getattr(self, f.name).add(s)
336 for ent in entities:
337 self.merge_fields(ent)
339 post_merge_with.send(sender=origin, instance=self, entities=entities)
341 for ent in entities:
342 ent.delete()
344 def duplicate(self):
345 origin = self.__class__
346 pre_duplicate.send(sender=origin, instance=self)
347 # usually, copying instances would work like
348 # https://docs.djangoproject.com/en/4.2/topics/db/queries/#copying-model-instances
349 # but we are working with abstract classes,
350 # so we have to do it by hand using model_to_dict:(
351 objdict = model_to_dict(self)
353 # remove unique fields from dict representation
354 unique_fields = [field for field in self._meta.fields if field.unique]
355 for field in unique_fields:
356 logger.info(f"Duplicating {self}: ignoring unique field {field.name}")
357 objdict.pop(field.name, None)
359 # remove related fields from dict representation
360 related_fields = [
361 field for field in self._meta.get_fields() if field.is_relation
362 ]
363 for field in related_fields:
364 objdict.pop(field.name, None)
366 newobj = type(self).objects.create(**objdict)
368 for field in related_fields:
369 # we are not using `isinstance` because we want to
370 # differentiate between different levels of inheritance
371 if type(field) is ForeignKey:
372 setattr(newobj, field.name, getattr(self, field.name))
373 if type(field) is ManyToManyField:
374 objfield = getattr(newobj, field.name)
375 values = getattr(self, field.name).all()
376 objfield.set(values)
378 newobj.save()
379 post_duplicate.send(sender=origin, instance=self, duplicate=newobj)
380 return newobj
382 duplicate.alters_data = True
384 def uri_set(self):
385 ct = ContentType.objects.get_for_model(self)
386 return (
387 ContentType.objects.get(app_label="uris", model="uri")
388 .model_class()
389 .objects.filter(content_type=ct, object_id=self.id)
390 .all()
391 )
393 def uri_set_with_importer(self):
394 return [uri for uri in self.uri_set() if self.valid_import_url(uri.uri)]
397class SimpleLabelModel(GenericModel):
398 label = models.CharField(
399 blank=True, default="", max_length=4096, verbose_name=_("label")
400 )
402 class Meta:
403 abstract = True
404 ordering = ["label"]
406 def __str__(self):
407 return self.label or force_str(_("No label"))
409 @classmethod
410 def create_from_string(cls, string):
411 return cls.objects.create(label=string)