Login

Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values

Author:
darklow
Posted:
January 28, 2013
Language:
Python
Version:
1.4
Tags:
ForeignKey Filter SimpleListFilter
Score:
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)

More like this

  1. Limit ForeignKey filter values to those that have a relationship with current model by overclocked 4 years, 7 months ago
  2. User manager by diverman 5 years, 11 months ago
  3. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 4 years, 9 months ago
  4. JSON fixtures of Intl. country codes & dial-codes by dibau_naum_h 4 years, 10 months ago
  5. Search child models in django admin changelist by navedr 9 months ago

Comments

Please login first before commenting.