Django admin: how can I filter an entire field for a specific range of values

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

+6
django django-admin django-admin-filters
source share
4 answers

What you are looking for is http://djangosnippets.org/snippets/587/ - the snippet is kind of old, but works fine after additional minor changes.

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

+1
source share

You can filter the field, something like this, using the queryset() function ... I 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 a dict in lookups() and return it according to age

  def lookups(self, request, model_admin): return [ (1, '5-21'), (2, '22-35'), (3, '35-60') ] 
+1
source share

I just want the filtered version of the list view that you get through the link (say, as a list), for example, to view only the related elements of the 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 lead you to view the list for "Reciepts", but only to those associated with the selected account.

If you need a filter that appears in the sidebar, you can try this snippet or this

0
source share

Based on another answer on a related question , I found out that there is an officially registered way to do this starting with version 1.4 . It even includes an example of filtering by date.

However, the snippet response snippet is also interesting because it simply adds django style parameters to the URL, which is a different solution than the official documentation example.

0
source share

All Articles