diff options
author | Étienne Loks <etienne.loks@iggdrasil.net> | 2025-02-26 11:59:08 +0100 |
---|---|---|
committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2025-02-26 11:59:08 +0100 |
commit | 779a48a37e632c8cbc9c1560cc0724583ea6e467 (patch) | |
tree | 4e6c7a64ed6fa200ab1006cd6220edfbac6ed126 /ishtar_common | |
parent | 5d977a9fa48d08f187184f1ca9f2fb94aeab2148 (diff) | |
download | Ishtar-779a48a37e632c8cbc9c1560cc0724583ea6e467.tar.bz2 Ishtar-779a48a37e632c8cbc9c1560cc0724583ea6e467.zip |
✨ generic autocomplete: put first exact match - add parent to search
Diffstat (limited to 'ishtar_common')
-rw-r--r-- | ishtar_common/views.py | 25 |
1 files changed, 22 insertions, 3 deletions
diff --git a/ishtar_common/views.py b/ishtar_common/views.py index f686709a0..81283d118 100644 --- a/ishtar_common/views.py +++ b/ishtar_common/views.py @@ -516,14 +516,33 @@ def get_autocomplete_generic(model, extra=None): def func(request): q = request.GET.get("term") query = Q(**extra) + nb = 0 + objects = [] + has_parent = hasattr(model, "parent") if not q: q = "" + else: + query_exact = query & Q(label__iexact=q) + query_exact = model.objects.filter(query_exact) + nb = query_exact.count() + objects = list(query_exact.all()) for q in q.split(" "): if not q: continue - query = query & Q(label__icontains=q) - limit = 20 - objects = model.objects.filter(query).distinct()[:limit] + sub_q = Q(label__icontains=q) + if has_parent: + sub_q |= Q(parent__label__icontains=q) + sub_q |= Q(parent__parent__label__icontains=q) + sub_q |= Q(parent__parent__parent__label__icontains=q) + query = query & (sub_q) + limit = 20 - nb + if limit > 0: + sort = ["label"] + if has_parent: + sort = ["parent__label", "label"] + objects += list( + model.objects.filter(query).order_by(*sort).distinct()[:limit] + ) get_label = lambda x: x.full_label() if hasattr(x, "full_label") else str(x) data = json.dumps([{"id": obj.pk, "value": get_label(obj)} for obj in objects]) return HttpResponse(data, content_type="text/plain") |