List filter and search results in admin
After overriding the method get_search_results
list_filter
doesn't work, but the search box works as I expect.
class NaruceniProduktiAdmin(admin.ModelAdmin):
search_fields = ('broj_narudbe', )
list_filter = ('date', 'status', )
list_display = (
'naziv_produkta', 'datum', 'narudba_broj', 'boja', 'velicina', 'cijena', 'kolicina',
'ukupna_cijena','korisnik_link','status','source_link',
)
actions = [dostupan, nedostupan, email_dostupan, placen, posalji_racun, poslan, isporucen, storniran, posalji_storno, ]
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(NaruceniProduktiAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
except ValueError:
search_term_as_int=search_term.strip()
queryset |= self.model.objects.filter(korisnik__ime__icontains=search_term_as_int)
if not queryset:
queryset |= self.model.objects.filter(korisnik__prezime__icontains=search_term_as_int)
else:
queryset = self.model.objects.filter(broj_narudbe=search_term_as_int)
return queryset, use_distinct
If I delete get_search_results
, then it list_filter
works as expected. I want to keep it, because I want the search boxes to work as I expect, but I also want to filter the list as usual.
Is there a way that I can use both of these methods together? And is there a reason why someone influences another?
source to share
The Changelist view first filters, then gives the filtered query as a parameter to your function get_search_results
. For it to work correctly, you must use an argument queryset
instead self.model.objects
.
def get_search_results(self, request, queryset, search_term):
new_queryset, use_distinct = super(NaruceniProduktiAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
except ValueError:
search_term_as_int=search_term.strip()
new_queryset |= queryset.filter(korisnik__ime__icontains=search_term_as_int)
if not new_queryset:
new_queryset |= queryset.filter(korisnik__prezime__icontains=search_term_as_int)
else:
new_queryset = queryset.filter(broj_narudbe=search_term_as_int)
return new_queryset, use_distinct
source to share