From ad4b9dc86bd90f8324049efc346aabc443bb015d Mon Sep 17 00:00:00 2001 From: Guido Longoni Date: Wed, 5 Jul 2023 14:33:56 +0200 Subject: [PATCH] Autoselect (senza propagazione su altri campi) --- django/contatti_app/drilldown_autocomplete.py | 8 +++++++- django/static/admin/js/autocomplete.js | 11 +++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/django/contatti_app/drilldown_autocomplete.py b/django/contatti_app/drilldown_autocomplete.py index b94a4e0..83e360e 100644 --- a/django/contatti_app/drilldown_autocomplete.py +++ b/django/contatti_app/drilldown_autocomplete.py @@ -61,11 +61,14 @@ class DrillDownAutocompleteJsonView(AutocompleteJsonView): def get_queryset(self): """Return queryset based on ModelAdmin.get_search_results().""" qs = super().get_queryset().only() + self.autoselect = False # print('Prima:',qs.query,'\n\n') if hasattr(self, 'linkedfields'): drilldown_filter_conditions = Q(**self.drilldown_filter_data) qs = qs.annotate(ddok=Max(Case(When(drilldown_filter_conditions, then=Value( 1)), default=Value(0)))).order_by('-ddok', *qs.query.order_by) + if qs.filter(ddok=1).count() == 1: + self.autoselect = True # print('Dopo:',qs.query,'\n\n') else: qs = qs.annotate(ddok=Value(1)) @@ -76,7 +79,10 @@ class DrillDownAutocompleteJsonView(AutocompleteJsonView): Convert the provided model object to a dictionary that is added to the results list. """ - return {"id": str(getattr(obj, to_field_name)), "text": str(obj), "ddok": obj.ddok} + out = {"id": str(getattr(obj, to_field_name)), "text": str(obj), "ddok": obj.ddok} + if self.autoselect and obj.ddok == 1: + out['autoselect'] = True + return out class DrillDownAutocompleteMixin(AutocompleteMixin): diff --git a/django/static/admin/js/autocomplete.js b/django/static/admin/js/autocomplete.js index 9343219..3ebaa75 100644 --- a/django/static/admin/js/autocomplete.js +++ b/django/static/admin/js/autocomplete.js @@ -23,8 +23,8 @@ if (linkedfields.hasOwnProperty(i)) { var remote_field = linkedfields[i]; var field_id = element.dataset.select2Id; - var remote_id = field_id.slice(0,field_id.length-field_name.length)+remote_field; - var value = document.querySelectorAll('[data-select2-id=' + remote_id +'].admin-autocomplete')[0].value; + var remote_id = field_id.slice(0, field_id.length - field_name.length) + remote_field; + var value = document.querySelectorAll('[data-select2-id=' + remote_id + '].admin-autocomplete')[0].value; if (value !== '') { //console.log(field + '=' + value); linkedfields_obj[remote_field] = value; @@ -49,6 +49,13 @@ styleClass = 'drilldown_ko'; } container.classList.add(styleClass); + if (item.hasOwnProperty('autoselect')) { + if ($(element).select2('data').length == 0) { + $(element).select2("trigger", "select", { + data: item + }) + } + } } return $('').text(item.text); }