Skip to main content
 首页 » 编程设计

python之Django 管理中的自定义过滤器

2025年05月04日37Renyi-Fan

我有一个模型如下

class Person: 
  name = models.CharField() 
  city = models.CharField() 
  phone = models.CharField() 

我想在管理页面创建一个过滤器,过滤器应该是基于电话的,即

valid phone(having 10 digits) 
invalid phone 

我不想创建验证。我只想过滤掉谁拥有有效电话和无效电话。 谢谢

请您参考如下方法:

创建自定义列表过滤器类。有一个 example in the docs 这可以适用于您的情况。

from django.contrib import admin 
 
class ValidPhoneListFilter(admin.SimpleListFilter): 
    # Human-readable title which will be displayed in the 
    # right admin sidebar just above the filter options. 
    title = _('valid phone') 
 
    parameter_name = 'valid_phone' 
 
    def lookups(self, request, model_admin): 
        return ( 
            ('valid', _('valid phone')), 
            ('invalid', _('invalid phone')), 
        ) 
 
    def queryset(self, request, queryset): 
        if self.value() == 'valid': 
            return queryset.filter(phone__regex=r'^\d{10}$') 
        if self.value() == 'invalid': 
            return queryset.exclude(phone__regex=r'^\d{10}$') 

然后将您的列表过滤器类包含在模型管理员的 list_filter 中。

class PersonAdmin(admin.ModelAdmin): 
    list_filter = (ValidPhoneListFilter,)