在Django中按非字段过滤

时间:2013-10-25 13:52:32

标签: python django filter

我想通过django应用的管理页面中的非字段列进行过滤。例如,我可以拥有以下内容:

class Subject(models.Model)
    name = models.CharField(max_length=100)
    def __unicode__(self):
        return self.name

class Student(models.Model)
    name = models.CharField(max_length=100)
    subject = models.ForeignKey(Subject)
    def __unicode__(self):
        return self.name

class School(models.Model)
    school = models.CharField(max_length=100)
    student = models.ForeignKey(Student)

    def subject(self)
        return self.student.subject.name

我在admin.py中有以下内容

class SchoolAdmin(admin.ModelAdmin):
  list_display = ('school', 'student', 'subject')
  list_filter = ('school', 'student', 'subject')

admin.site.register(School, SchoolAdmin)

然而,这不起作用,因为我无法过滤主题,因为它没有引用字段?有谁知道这样做的最佳方式?通过搜索它看起来像SimpleListFilter可以做的伎俩,但我是python和django的新手,并且无法解决如何为我的例子实现这一点。

提前致谢

1 个答案:

答案 0 :(得分:6)

试试这个:

class SchoolAdmin(admin.ModelAdmin):
  list_display = ('school', 'student__name', 'student__subject__name')
  list_filter = ('school', 'student__name', 'student__subject__name')

admin.site.register(School, SchoolAdmin)