Autoselect (senza propagazione su altri campi)

my-submodulepoetico
Guido Longoni 2023-07-05 14:33:56 +02:00
parent 6a6f956785
commit ad4b9dc86b
2 changed files with 16 additions and 3 deletions

View File

@ -61,11 +61,14 @@ class DrillDownAutocompleteJsonView(AutocompleteJsonView):
def get_queryset(self): def get_queryset(self):
"""Return queryset based on ModelAdmin.get_search_results().""" """Return queryset based on ModelAdmin.get_search_results()."""
qs = super().get_queryset().only() qs = super().get_queryset().only()
self.autoselect = False
# print('Prima:',qs.query,'\n\n') # print('Prima:',qs.query,'\n\n')
if hasattr(self, 'linkedfields'): if hasattr(self, 'linkedfields'):
drilldown_filter_conditions = Q(**self.drilldown_filter_data) drilldown_filter_conditions = Q(**self.drilldown_filter_data)
qs = qs.annotate(ddok=Max(Case(When(drilldown_filter_conditions, then=Value( qs = qs.annotate(ddok=Max(Case(When(drilldown_filter_conditions, then=Value(
1)), default=Value(0)))).order_by('-ddok', *qs.query.order_by) 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') # print('Dopo:',qs.query,'\n\n')
else: else:
qs = qs.annotate(ddok=Value(1)) 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 Convert the provided model object to a dictionary that is added to the
results list. 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): class DrillDownAutocompleteMixin(AutocompleteMixin):

View File

@ -49,6 +49,13 @@
styleClass = 'drilldown_ko'; styleClass = 'drilldown_ko';
} }
container.classList.add(styleClass); container.classList.add(styleClass);
if (item.hasOwnProperty('autoselect')) {
if ($(element).select2('data').length == 0) {
$(element).select2("trigger", "select", {
data: item
})
}
}
} }
return $('<span class="' + styleClass + '"></span>').text(item.text); return $('<span class="' + styleClass + '"></span>').text(item.text);
} }