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

4

13

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.

Ironbound answered 30/10, 2010 at 19:51 Comment(4)
better fit to webmasters.stackexchange.com/questionsBoost
@Boost I don't think so; this is a programming question.Ironbound
yes i know but better fir to webmastersBoost
I completely disagree, @svisstack. This is a pure programming question; it has nothing to do with server configuration, SEO, SMO, or design sensibilities.Sectional
A
3

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')
    ]
Adjoin answered 6/2, 2017 at 11:23 Comment(0)
S
2

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

Smarten answered 6/6, 2011 at 7:57 Comment(0)
G
0

I you simply want a filtered version of the list view, that you access via a link (say in the list view), for example to view only the related items of a model, you do something like this:

def admin_view_receipts(self, object):
    url = urlresolvers.reverse('admin:invoice_%s_changelist'%'receipt')
    params = urllib.urlencode({'invoice__id__exact': object.id})
    return '<a href="%s?%s">Receipts</a>' % (url, params)
admin_view_receipts.allow_tags = True
admin_view_receipts.short_description = 'Receipts'

This will take you to a list view for 'Reciepts', but only those linked to the selected Invoice.

If you want a filter that displays in the sidebar, you could try this snippet or this

Guideline answered 31/10, 2010 at 7:42 Comment(0)
E
0

Based on another answer for a related question, I learnt that there is an officially documented way to do that since version 1.4. It even includes an example of filtering by date.

Still, the snippet in the sorin answer is also interesting, because it just adds django-style parameters to the URL, which is a different solution than the official documentation example.

Everyman answered 25/7, 2014 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.