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
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 months, 3 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 3 months, 1 week ago
- Browser-native date input field by kytta 4 months, 3 weeks ago
- Generate and render HTML Table by LLyaudet 5 months ago
- My firs Snippets by GutemaG 5 months, 1 week ago