After I override the get_search_results
method, list_filter
is not working but the search field 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 remove get_search_results
, then list_filter
works as expected. I want to keep it because I want the search fields to work how I expect, but I also want the list filtering to work as it normally does.
Is there a way that I can use both of these together? And is there a reason why one influences the other?
Changelist view first makes filtering, then it gives filtered queryset as parameter to your get_search_results
function. To make it work properly you should use queryset
argument instead of self.model.objects
.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With