Django: list_filter and foreign key fields
Django supports list_filter with foreign key fields
# models.py:class Foo(models.Model): name = models.CharField(max_length=255) def __unicode__(self): return self.nameclass Bar(models.Model): name = models.CharField(max_length=255) foo = models.ForeignKey(Foo)# admin.py:class BarAdmin(admin.ModelAdmin): list_filter = ('foo__name')
From documentation: Field names in list_filter can also span relations using the __ lookup
Well, the docs say that you can may use ForeignKey
field types in list_filter
:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
An example:
# models.py:class Foo(models.Model): name = models.CharField(max_length=255) def __unicode__(self): return self.nameclass Bar(models.Model): name = models.CharField(max_length=255) foo = models.ForeignKey(Foo)# admin.py:class BarAdmin(admin.ModelAdmin): list_filter = ('foo')
If you want to filter by a field from the related model, there's a patch on the way to make this work (will probably be merged into 1.2 as it seems):
solution from this page worked for me http://www.hoboes.com/Mimsy/hacks/fixing-django-124s-suspiciousoperation-filtering/
define
class SmarterModelAdmin(admin.ModelAdmin): valid_lookups = () def lookup_allowed(self, lookup, *args, **kwargs): if lookup.startswith(self.valid_lookups): return True return super(SmarterModelAdmin, self).lookup_allowed(lookup, *args, **kwargs)
then allow the lookup for certain foreign key field
class PageAdmin(SmarterModelAdmin): valid_lookups = ('parent')