python Django管理员:按范围筛选字段

xwbd5t1u  于 2023-01-11  发布在  Python
关注(0)|答案(3)|浏览(134)

我有一个模型叫Person,Person有名字/姓氏和年龄等字段,现在我想实现的是在django admin中有一个过滤器,可以过滤一些自定义范围的年龄,比如10-15。
在阅读了一些帖子后,我最好的拍摄是:

class RangeFilter(SimpleListFilter):
    title = 'Age filter'
    parameter_name = 'age'
    
    def lookups(self, request, model_admin):
        
        return [
            (1, '0-5'),
            (2, '5-10'),
            (3, '10-15'),
            (4, '15-20')]

    def queryset(self, request, queryset):
        filt_age = request.GET.get('age')
        return queryset.filter(
                    age__range=self.age_dict[filt_age]
                )

但这会产生错误“RangeFilter”对象没有属性“age_dict”。

cqoc49vn

cqoc49vn1#

你的意思大概是:

def lookups(self, request, model_admin):    
    return ('1', '0-5'),('2', '5-10'), ('3', '10-15'), ('4', '15-20')

def queryset(self, request, queryset):
    filt_age = request.GET.get('age')
    age_dict = dict(self.lookups(None, None))
    if age_dict.get(filt_age):
        return queryset.filter(age__range=age_dict[filt_age])
    return queryset

return queryset.filter(age__range=dict(self.lookups(None, None))[filt_age])
jaxagkaj

jaxagkaj2#

很难猜出你想做什么,我的尝试是:

class RangeFilter(SimpleListFilter):
    title = 'Age filter'
    parameter_name = 'age'

    age_dict = {
        1: (0, 5),
        2: (5, 10),
        3: (10, 15),
        4: (15, 20)
    }

    def lookups(self, request, model_admin):
        return [(k, '-'.join(map(str, v))) for k, v in self.age_dict.items()]

    def queryset(self, request, queryset):
        filt_age = request.GET.get('age')
        return queryset.filter(
            age__range=self.age_dict[filt_age]
        )
k4aesqcs

k4aesqcs3#

我不知道你想做什么,但我给你下面的例子来过滤人的年龄以下的文件:

# "store/models.py"

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)
    age =  models.IntegerField()
    
    def __str__(self):
        return self.name
# "store/admin.py"

from django.contrib import admin
from .models import Person

class PersonAgeFilter(admin.SimpleListFilter):
    title = 'Person Age Filter'
    parameter_name = 'age'

    def lookups(self, request, model_admin):
        return (
            ("0-19", '0-19 years'),
            ("20-39", '20-39 years'),
            ("40-59", '40-59 years'),
            ("60<=", '60 years and over'),
        )

    def queryset(self, request, queryset):
        if self.value() == '0-19':
            return queryset.filter(age__lte=19)
        if self.value() == '20-39':
            return queryset.filter(age__range=(20, 39))
        if self.value() == '40-59':
            return queryset.filter(age__range=(40, 59))
        if self.value() == '60<=':
            return queryset.filter(age__gte=60)

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    list_filter = (PersonAgeFilter,)

然后,过滤器部分出现,有5个人,如下所示:

然后点击20-39 year,5人过滤为3人,如下图所示:

相关问题