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)
More like this
- Django Settings Assignment Expressions aka Walrus Operator example by webology 3 weeks, 1 day ago
- codigo alto nivel by MrRocklion 2 months, 2 weeks ago
- Load template from specific app by Krzysiek555 3 months, 1 week ago
- PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
- "Magic Link" Management Command by webology 8 months, 2 weeks ago