自定义管理页面 - list_filter的第一个字母

时间:2015-10-24 19:53:02

标签: django django-admin

我有自定义管理子页面的课程:

class SerchPlaceAdmin(admin.ModelAdmin):
    list_filter = ('nameplace',)

nameplacemodels.CharField。我想用第一个字母过滤记录。请看printcree enter image description here n

2 个答案:

答案 0 :(得分:4)

这应该对您有用,有关详细信息,请参阅docs

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


class FirstLetterListFilter(admin.SimpleListFilter):
    title = _('First letter')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'letter'

    def lookups(self, request, model_admin):
        return (
            ('A', _('A')),
            ('B', _('B'))
        )

    def queryset(self, request, queryset):
        return queryset.filter(nameplace__startswith=self.value())

class SerchPlaceAdmin(admin.ModelAdmin):
    list_filter = (FirstLetterListFilter,)

答案 1 :(得分:0)

接受的答案对我来说有一个问题:它会破坏未经过滤的视图。这由以下if方法中的queryset - 子句修复。

此外,下面的代码搜索不区分大小写,只显示返回结果的字母,包括计数。

class FirstLetterFilter(SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = 'First Letter'

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'letter'
    letters = list(string.ascii_uppercase)

    def lookups(self, request, model_admin):
        qs = model_admin.get_queryset(request)
        lookups = []
        for letter in self.letters:
            count = qs.filter(name__istartswith=letter).count()
            if count:
                lookups.append((letter, '{} ({})'.format(letter, count)))
        return lookups

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        filter_val = self.value()
        if filter_val in self.letters:
            return queryset.filter(name__istartswith=self.value())

当然,对于大型表,我建议将第一个字母提取到自己的列中,并在其上放置一个索引(不区分大小写)。

对于不区分大小写的搜索符合大小写不敏感的排序,请将其添加到ModelAdmin中:

class MyModelAdmin(ModelAdmin):
    list_display = ('name',)
    search_fields = ['name']

    def get_ordering(self, request):
        return [Lower('name')]