开发者

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

开发者 https://www.devze.com 2023-01-22 23:19 出处:网络
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 on开发者_JAVA百

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 on开发者_JAVA百科ly want to display Person records where age is between 45 and 65.


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号