From 779a48a37e632c8cbc9c1560cc0724583ea6e467 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Wed, 26 Feb 2025 11:59:08 +0100 Subject: ✨ generic autocomplete: put first exact match - add parent to search MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ishtar_common/views.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) (limited to 'ishtar_common/views.py') 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") -- cgit v1.2.3