Django: list_filter and foreign key fields

前端 未结 6 1828
野性不改
野性不改 2021-02-07 00:54

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 h

6条回答
  •  我在风中等你
    2021-02-07 01:38

    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

提交回复
热议问题