Home > Blockchain >  Django admin: Filter field by range
Django admin: Filter field by range

Time:08-06

Hi i have a model called Person. Person has fields like name/surname and age. Now what I want to achieve is to have a filter in django admin that can filter age in some custom ranges so 10-15

after reading some posts my best shoot is

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]
                )

but this yields an error 'RangeFilter' object has no attribute 'age_dict'

CodePudding user response:

probably you mean:

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

but it can be a Exeption, if filt_age key not exists in dict.

CodePudding user response:

It's a bit hard to guess what are you trying to do, my attempt would be:

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]
        )
  • Related