Django: list_filter and foreign key fields

前端 未结 6 1825
野性不改
野性不改 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:44

    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

提交回复
热议问题