在管理员中列出过滤器和搜索结果

在管理员中列出过滤器和搜索结果

本文介绍了在管理员中列出过滤器和搜索结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我覆盖 get_search_results 方法后,list_filter 无法正常工作,但搜索字段按预期工作.

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

如果我删除 get_search_results,则 list_filter 会按预期工作.我想保留它,因为我希望搜索字段按我的预期工作,但我也希望列表过滤能像往常一样工作.

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 视图首先进行过滤,然后将过滤后的查询集作为参数提供给您的 get_search_results 函数.为了使其正常工作,您应该使用 queryset 参数而不是 self.model.objects.

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

这篇关于在管理员中列出过滤器和搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:47