Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin: How do I filter on an integer field for a specific range of values

How do I create a filter in Django Admin to only display records where an integer value lies between two values? For example, if I have a model Person, which has an age attribute, and I only want to display Person records where age is between 45 and 65.

like image 207
FunLovinCoder Avatar asked Oct 30 '10 19:10

FunLovinCoder


2 Answers

You can Filter the field some what like this by using queryset() Function ... I had used SimpleListFilter

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

And create dict in lookups() and return it According to the age

def lookups(self, request, model_admin):
    return [
        (1, '5-21'),
        (2, '22-35'),
        (3, '35-60')
    ]
like image 72
Jay Dave Avatar answered Sep 21 '22 12:09

Jay Dave


What you are looking is http://djangosnippets.org/snippets/587/ - the snippet is kinda old but works just fine after an additional minor change.

I uploaded the patched version at https://gist.github.com/1009903

like image 27
sorin Avatar answered Sep 18 '22 12:09

sorin