Login

Compact list_filter with counter

Author:
fab10m
Posted:
February 15, 2011
Language:
Python
Version:
1.1
Tags:
admin-interface compact list_filter
Score:
1 (after 1 ratings)

This is an extension of the fantastic snippet "Compact list_filter" written by onlinehero. Follow his instructions for the installation. My version add the number of filtered objects beside the label of the filters defined by the list_filter property.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec
from django.utils.encoding import smart_unicode
from django.db.models import Count

class CustomChoiceFilterSpec(ChoicesFilterSpec):
	def __init__(self, f, request, params, model, model_admin):	   
		super(CustomChoiceFilterSpec, self).__init__(f, request, params, model, model_admin)
		self.lookup_kwarg = '%s__id__exact' % f.name # Change this to match the search of your object
		self.lookup_val = request.GET.get(self.lookup_kwarg, None)
		self.objects = model.objects.all()
		self.foreign_key = f.name
		self.foreign_key_count = {} 
		for item in model.objects.values(f.name).annotate(count=Count('pk')):
			self.foreign_key_count[item[f.name]] = item['count']

	def choices(self, cl):
		yield {'selected': self.lookup_val is None,
			   'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
			   'display': ('All')}
		items = set([getattr(i, self.foreign_key) for i in self.objects])
		for k in items:
			if k is None:
				kk = None
			else:
				kk = k.id
			yield {'selected': smart_unicode(k) == self.lookup_val,
					'query_string': cl.get_query_string({self.lookup_kwarg: kk}), # Change .id to match what you are searching for
					'display': '%s (%s)' % (k, self.foreign_key_count[kk])}

FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'compact_filter', False), CustomChoiceFilterSpec))

More like this

  1. Generic compact list_filter with counts by anentropic 3 years, 5 months ago
  2. Compact list_filter by onlinehero 5 years, 5 months ago
  3. Foreign Key list_filter wthout custom FilterSpec by haileris23 5 years, 5 months ago
  4. Random code tag by aaloy 7 years, 11 months ago
  5. Filter by taggit tags in the admin by flupke 3 years, 8 months ago

Comments

Please login first before commenting.