Coverage for apis_core/apis_entities/autocomplete3.py: 44%
25 statements
« prev ^ index » next coverage.py v7.6.8, created at 2024-12-20 09:24 +0000
« prev ^ index » next coverage.py v7.6.8, created at 2024-12-20 09:24 +0000
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3import json
5from dal import autocomplete
6from django import http
7from django.contrib.contenttypes.models import ContentType
9from apis_core.apis_entities.utils import get_entity_classes
10from apis_core.apis_relations.models import Property
13class PropertyAutocomplete(autocomplete.Select2ListView):
14 # These constants are set so that they are defined in one place only and reused by fetching them elsewhere.
15 SELF_SUBJ_OTHER_OBJ_STR = "self_subj_other_obj"
16 SELF_OBJ_OTHER_SUBJ_STR = "self_obj_other_subj"
18 def get_autocomplete_property_choices(self, self_model, other_model, search_str):
19 contenttypes = [
20 ContentType.objects.get_for_model(model) for model in get_entity_classes()
21 ]
22 self_contenttype = next(
23 filter(lambda x: x.model == self_model.lower(), contenttypes)
24 )
25 other_contenttype = next(
26 filter(lambda x: x.model == other_model.lower(), contenttypes)
27 )
29 rbc_self_subj_other_obj = Property.objects.filter(
30 subj_class=self_contenttype,
31 obj_class=other_contenttype,
32 name_forward__icontains=search_str,
33 )
34 rbc_self_obj_other_subj = Property.objects.filter(
35 subj_class=other_contenttype,
36 obj_class=self_contenttype,
37 name_reverse__icontains=search_str,
38 )
39 choices = []
40 for rbc in rbc_self_subj_other_obj:
41 choices.append(
42 {
43 # misuse of the id item as explained above
44 "id": f"id:{rbc.pk}__direction:{self.SELF_SUBJ_OTHER_OBJ_STR}",
45 "text": rbc.name_forward,
46 }
47 )
48 for rbc in rbc_self_obj_other_subj:
49 choices.append(
50 {
51 # misuse of the id item as explained above
52 "id": f"id:{rbc.pk}__direction:{self.SELF_OBJ_OTHER_SUBJ_STR}",
53 "text": rbc.name_reverse,
54 }
55 )
56 return choices
58 def get(self, request, *args, **kwargs):
59 more = False
60 choices = self.get_autocomplete_property_choices(
61 kwargs["entity_self"], kwargs["entity_other"], self.q
62 )
63 return http.HttpResponse(
64 json.dumps(
65 {"results": choices, "pagination": {"more": more}, "abcde": "0"}
66 ),
67 content_type="application/json",
68 )