在我覆盖get_search_results
方法后,list_filter
无法正常工作,但搜索字段可以正常运行。
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
如果我删除get_search_results
,则list_filter
按预期工作。我想保留它,因为我希望搜索字段能够达到预期效果,但我也希望列表过滤能够像往常一样工作。
有没有办法可以同时使用这两种方法?是否有人影响另一方?
答案 0 :(得分:2)
更改列表视图首先进行过滤,然后将过滤后的查询集作为参数提供给get_search_results
函数。为了使其正常工作,您应使用queryset
参数而不是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