Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I know question was about Django 1.3 however you mentioned on soon upgrading to 1.4. Also to people, like me who was looking for solution for 1.4, but found this entry, i decided to show full example of using <a href="https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter">SimpleListFilter</a> (available Django 1.4) to show only referenced (related, used) foreign key values</p> <pre class="lang-py prettyprint-override"><code>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) </code></pre> <p>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.</p> <p>Original idea from <a href="http://jmduke.net/post/39953950546/custom-admin-filters-in-django">here</a>. Big thanks to author. Improved class names for better clarity and use of model_admin.model instead of hardcoded model name.</p> <p>Example also available in Django Snippets: <a href="http://djangosnippets.org/snippets/2885/">http://djangosnippets.org/snippets/2885/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload