- January 28, 2013
- ForeignKey Filter SimpleListFilter
- 0 (after 0 ratings)
Since Django 1.4 you can create your own filters for change list view. If you want to show just used/related items in filter chooser you can use this snippet.
Original idea from here. Big thanks to author.
Improved class names for better clarity and use of model_admin.model instead of hardcoded model name.
In example you can see two models - City and Country. City has ForeignKey to Country. If you use regular list_filter = ('country',) you will have all the countries in the chooser. This snippet however filters only related countries - the ones that have at least one relation to city.
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 31 32 33 34 35 36 37 38 39 40
from django.contrib.admin import SimpleListFilter # admin.py class CountryFilter(SimpleListFilter): title = 'country' # or use _('country') for translated title parameter_name = 'country' def lookups(self, request, model_admin): countries = set([c.country for c in model_admin.model.objects.all()]) return [(c.id, c.name) for c in countries] # You can also use hardcoded model name like "Country" instead of # "model_admin.model" if this is not direct foreign key filter def queryset(self, request, queryset): if self.value(): return queryset.filter(country__id__exact=self.value()) else: return queryset # # Example setup and usage # # models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=64) class City(models.Model): name = models.CharField(max_length=64) country = models.ForeignKey(Country) # admin.py from django.contrib.admin import ModelAdmin class CityAdmin(ModelAdmin): list_filter = (CountryFilter,) admin.site.register(City, CityAdmin)