Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: list_filter and foreign key fields

Django doesn't support getting foreign key values from list_display or list_filter (e.g foo__bar). I know you can create a module method as a workaround for list_display, but how would I go about to do the same for list_filter? Thanks.

like image 559
Dan Avatar asked Jan 14 '10 15:01

Dan


3 Answers

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.name  class 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

like image 184
Stoyan Kostov Avatar answered Sep 22 '22 15:09

Stoyan Kostov


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.name

class 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):

http://code.djangoproject.com/ticket/3400

like image 27
Haes Avatar answered Sep 22 '22 15:09

Haes


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')
like image 32
opp Avatar answered Sep 22 '22 15:09

opp