ModelAdmin Scagairí LiostaLink to this heading

Is féidir le ranganna ModelAdmin scagairí liosta a shainiú atá le feiceáil i mbarra taobh na láimhe deise de leathanach liosta athraithe an riaracháin, mar a léirítear sa scáileán seo a leanas:

/ga/6.1/_images/list_filter.png

Chun scagadh in aghaidh an réimse a ghníomhachtú, socraí:attr: ModelAdmin.list_filter chuig liosta nó tupla eilimintí, áit a bhfuil gach eilimint ar cheann de na cineálacha seo a leanas:

  • Ainm réimse.

  • Fo-aicme de Django.Contrib.admin.SimpleListFilter.

  • 2 tuple ina bhfuil ainm réimse agus fo-aicme de Django.Contrib.admin.FieldListFilter.

Féach na samplaí thíos chun plé a dhéanamh ar gach ceann de na roghanna seo chun list_filter` a shainiú.

Ainm réimse a úsáidLink to this heading

Is é an rogha is simplí ná na hainmneacha réimse riachtanacha a shonrú ó do shamhail.

Ba chóir go mbeadh Booleanfield, Charfield`, DateField, DateTimeField`, Integerfield, ForeignKey` nó ManyTomanyField, ManyToManyField, mar shampla:

Code
class PersonAdmin(admin.ModelAdmin):
    list_filter = ["is_staff", "company"]

Is féidir le hainmneacha réimse i list_filter` caidrimh a scaipeadh freisin ag baint úsáide as an lorg __, mar shampla:

Code
class PersonAdmin(admin.UserAdmin):
    list_filter = ["company__name"]

Ag baint úsáide as SimpleListFilterLink to this heading

Le haghaidh scagadh saincheaptha, is féidir leat do scagaire liosta féin a shainiú trí “Django.Contrib.Admin.SimpleListFilter” a fho-aicmiú. Ní mór duit na tréithe `title agus parameter_name a sholáthar, agus na modhanna lookups agus queryset a shárú, m.sh.:

Code
from datetime import date

from django.contrib import admin
from django.utils.translation import gettext_lazy as _


class DecadeBornListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _("decade born")

    # Parameter for the filter that will be used in the URL query.
    parameter_name = "decade"

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return [
            ("80s", _("in the eighties")),
            ("90s", _("in the nineties")),
        ]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or '90s')
        # to decide how to filter the queryset.
        if self.value() == "80s":
            return queryset.filter(
                birthday__gte=date(1980, 1, 1),
                birthday__lte=date(1989, 12, 31),
            )
        if self.value() == "90s":
            return queryset.filter(
                birthday__gte=date(1990, 1, 1),
                birthday__lte=date(1999, 12, 31),
            )


class PersonAdmin(admin.ModelAdmin):
    list_filter = [DecadeBornListFilter]

Ag baint úsáide as ainm réimse agus FieldlistFilter follasachLink to this heading

Mar fhocal scoir, más mian leat cineál scagaire follasach a shonrú le húsáid le réimse féadfaidh tú mír list_filter` a sholáthar mar 2-tuple, áit a bhfuil ainm réimse an chéad eilimint agus is aicme é an dara eilimint ag oidhreacht ó django.contrib.admin.fieldlistfilter, mar shampla:

Code
class PersonAdmin(admin.ModelAdmin):
    list_filter = [
        ("is_staff", admin.BooleanFieldListFilter),
    ]

Anseo úsáidfidh an réimse is_staff an BooleanFieldListFilter`. Ag sonrú ach ainm an réimse, úsáidfidh réimsí an scagaire cuí go huathoibríoch don chuid is mó de na cásanna, ach tugann an fhormáid seo deis duit an scagaire a úsáidtear

Taispeánann na samplaí seo a leanas ranganna scagaire atá ar fáil a chaithfidh tú roghnú isteach le húsáid.

Féadfaidh tú roghanna samhail ghaolmhara a theorannú leis na rudaí a bhaineann leis an ngaol sin ag baint úsáide as RelatedOnlyFieldListFilter:

Code
class BookAdmin(admin.ModelAdmin):
    list_filter = [
        ("author", admin.RelatedOnlyFieldListFilter),
    ]

Ag glacadh leis gur ForeignKey é údar` do mhúnla Úsáideora ``, cuirfidh seo teorainn leis na roghanna ``list_filter do na húsáideoirí a scríobh leabhar, in ionad gach úsáideoir a liostáil.

Is féidir leat luachanna folmha a scagadh ag baint úsáide as EmptyFieldListFilter`, atá in ann scagadh ar theagáin folamh agus ar neamhaill araon, ag brath ar an méid a cheadaíonn an réimse a stóráil:

Code
class BookAdmin(admin.ModelAdmin):
    list_filter = [
        ("title", admin.EmptyFieldListFilter),
    ]

By defining a filter using the __in lookup, it is possible to filter for any of a group of values. You need to override the expected_parameters method, and then specify the lookup_kwargs attribute with the appropriate field name. By default, multiple values in the query string will be separated with commas, but this can be customized via the list_separator attribute. The following example shows such a filter using the vertical-pipe character as the separator:

Code
class FilterWithCustomSeparator(admin.FieldListFilter):
    # custom list separator that should be used to separate values.
    list_separator = "|"

    def __init__(self, field, request, params, model, model_admin, field_path):
        self.lookup_kwarg = "%s__in" % field_path
        super().__init__(field, request, params, model, model_admin, field_path)

    def expected_parameters(self):
        return [self.lookup_kwarg]

De ghnáth ní bhfeictear scagairí liosta ach amháin má tá níos mó ná rogha amháin ag an scagaire. Rialaíonn modh ``has_output () ``scagaire cibé an bhfuil sé le feiceáil nó nach bhfuil.

Is féidir teimpléad saincheaptha a shonrú chun scagaire liosta a rindreáil:

Code
class FilterWithCustomTemplate(admin.SimpleListFilter):
    template = "custom_template.html"

Féach an teimpléad réamhshocraithe a sholáthraíonn Django (admin/filter.html) le haghaidh sampla nithiúil.

GnéitheLink to this heading

De réir réamhshocraithe, is féidir comhaireamh do gach scagaire, ar a dtugtar gnéithe, a thaispeáint trí aistriú tríd an gChomhéadan riaracháin. Déanfar na comhaireanta seo a nuashonrú de réir na scagairí atá i bhfeidh Féach: attr: ModelAdmin.show_facets le haghaidh tuilleadh sonraí.