Coverage for apis_core/search/models.py: 43%
81 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 unicodedata
3from django.conf import settings
4from django.contrib.contenttypes.fields import GenericForeignKey
5from django.contrib.contenttypes.models import ContentType
6from django.contrib.postgres.indexes import GinIndex
7from django.contrib.postgres.search import (
8 SearchQuery,
9 SearchRank,
10 SearchVector,
11 SearchVectorField,
12)
13from django.db import models
14from django.db.models import Case, F, Field, Q, Value, When
15from django.db.models.functions import Greatest
16from django.db.models.lookups import PatternLookup
18from .utils import (
19 get_models_registered_for_search,
20 get_search_serialization_from_instance,
21 split_query_string_for_search,
22)
25@Field.register_lookup
26class ILike(PatternLookup):
27 """
28 We implement our own `ilike` lookup, because the `icontains`
29 lookup uses the sql `UPPER` function and matching functions
30 with a lookup index does not work.
31 """
33 lookup_name = "ilike"
35 def as_sql(self, compiler, connection):
36 lhs, lhs_params = self.process_lhs(compiler, connection)
37 rhs, rhs_params = self.process_rhs(compiler, connection)
38 params = (*lhs_params, *rhs_params)
39 return "%s::text ILIKE %s" % (lhs, rhs), params
42class SearchManager(models.Manager):
43 def search(
44 self, query_str: str, content_types=[], with_content=False, only_registered=True
45 ):
46 """
47 We combine multiple approaches to searching the entries.
48 We use the `search_vector` full text search on the title
49 and the content_text fields. Any calculated rank that is
50 lower than 0.01 is set to 0. We then store the maximum
51 value of the title rank times 2 and the content rank. This
52 is then used the primary means for ranking.
53 Then we look at the individual fields and give them weight
54 in the order title -> content_text, each both case-sensitive
55 & case insensitive. We match those fields for the whole
56 `query_str` as well as the individual parts.
57 Those checks are then also used as an overall filter, so only results
58 containing those strings are looked at and returned.
59 """
61 query = super().get_queryset()
62 search_config = getattr(settings, "SEARCH_SEARCHQUERY_CONFIG", None)
63 search_query = SearchQuery(
64 unicodedata.normalize("NFKD", query_str), config=search_config
65 )
66 query = query.annotate(
67 title_rank=SearchRank(F("title_search_vector"), search_query),
68 content_rank=Value(0.0),
69 )
70 if with_content:
71 query = query.annotate(
72 content_rank=SearchRank(F("content_search_vector"), search_query)
73 )
74 query = query.annotate(
75 title_rank=Case(
76 When(title_rank__gt=0.01, then=F("title_rank")), default=Value(0.0)
77 )
78 )
79 query = query.annotate(
80 content_rank=Case(
81 When(content_rank__gt=0.01, then=F("content_rank")), default=Value(0.0)
82 )
83 )
84 query = query.annotate(frank=Greatest(F("title_rank") * 2, "content_rank"))
86 lookups = {
87 "title__contains": 10,
88 "title__ilike": 9,
89 }
90 if with_content:
91 lookups["content_text__contains"] = 6
92 lookups["content_text__ilike"] = 5
94 parts = split_query_string_for_search(query_str)
95 q = Q()
96 w = []
98 weights = [0] * len(parts)
99 weights[0] = 2
100 for weight, part in zip(weights, parts):
101 for lookup, value in lookups.items():
102 q |= Q(**{lookup: part})
103 w += [When(**{lookup: part, "then": value + weight})]
105 query = query.filter(q).annotate(contains=Case(*w, default=0))
107 query = query.order_by("-frank", "-contains", "id")
109 if only_registered:
110 registered_cts = [
111 ContentType.objects.get_for_model(model)
112 for model in get_models_registered_for_search()
113 ]
114 query = query.filter(content_type__in=registered_cts)
115 if content_types:
116 query = query.filter(content_type__in=content_types)
117 return query
120class SearchEntry(models.Model):
121 """
122 An entry in the search table pointing to a Django model instance
123 """
125 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
126 object_id = models.PositiveIntegerField(null=True)
127 content_object = GenericForeignKey()
129 title = models.CharField(max_length=1024)
131 content = models.JSONField()
133 content_text = models.TextField(null=True)
135 title_search_vector = SearchVectorField()
136 content_search_vector = SearchVectorField()
138 objects = SearchManager()
140 class Meta:
141 app_label = "search"
142 unique_together = ["content_type", "object_id"]
143 indexes = [
144 models.Index(fields=["content_type", "object_id"]),
145 GinIndex(
146 name="generic_sea_content_text_gin",
147 fields=["content_text"],
148 opclasses=["gin_trgm_ops"],
149 ),
150 GinIndex(
151 name="generic_sea_title_gin",
152 fields=["title"],
153 opclasses=["gin_trgm_ops"],
154 ),
155 GinIndex(fields=["title_search_vector"]),
156 GinIndex(fields=["content_search_vector"]),
157 ]
159 @classmethod
160 def reindex_model_instance(cls, instance):
161 content_type = ContentType.objects.get_for_model(instance)
163 title = unicodedata.normalize("NFKD", str(instance))
165 serialization = get_search_serialization_from_instance(instance)
167 serialization_text = {k: str(v) for k, v in serialization.items() if v}
168 content_text = " ".join(serialization_text.values())
170 defaults = {
171 "title": title,
172 "content": serialization,
173 "content_text": content_text,
174 }
175 s, c = cls.objects.update_or_create(
176 content_type=content_type, object_id=instance.pk, defaults=defaults
177 )
178 s.title_search_vector = SearchVector("title", weight="A")
179 s.content_search_vector = SearchVector("content_text", weight="A")
180 s.save()
182 @classmethod
183 def delete_by_instance(cls, instance):
184 content_type = ContentType.objects.get_for_model(instance)
186 cls.objects.filter(content_type=content_type, object_id=instance.pk).delete()