Filter in Django Admin via a ManyToMany field with Through

My models.py:

class Subject(models.Model):
    name = models.CharField(max_length=200)

class Person(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True)

class PersonRole(models.Model):
    project = models.ForeignKey('Project', on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)

class Project(models.Model):

    title = models.CharField(max_length=200)
    person = models.ManyToManyField(Person, through=PersonRole)

Now, in my admin back-end I'd like to add a nice filtering with list_filter. This filter should make it possible to filter by the schools that a person is attached to a project. In other words, if John (belonging to school 'no. 1') is attached to project no. 3, I'd like the projects table on the backend to show only project no. 3. I suppose I should customise a simplelistfilter. First of all, though, I'm a bit stuck as to how to get the list of schools attached to the persons attached to a project.

My attempt so far is:

class PersonRole(models.Model):

    [...]

    def get_school(self):
        return self.person.school


class Project(models.Model):

    @admin.display(description='PI School')
    def get_PI_school(self):
        return [p for p in self.person.get_school()] 

admin.py:

class ProjectAdmin(admin.ModelAdmin):
    list_display = ("get_PI_school",) #This is just to see if the field is populated

With this, I get 'ManyRelatedManager' object has no attribute 'get_school'.

You use .get_school() on the PersonRole object:

class Project(models.Model):
    @admin.display(description='PI School')
    def get_PI_school(self):
        return [p.get_school() for p in self.personrole_set.all()]

We can boost efficiency by fetching the related Person and School in the same query:

class Project(models.Model):
    @admin.display(description='PI School')
    def get_PI_school(self):
        return [
            p.get_school()
            for p in self.personrole_set.select_related('person__school')
        ]

and you can filter to a PI role with:

class Project(models.Model):
    @admin.display(description='PI School')
    def get_PI_school(self):
        return [
            p.get_school()
            for p in self.personrole_set.filter(
                title__contains="Principal investigator"
            )
        ]

given of course your PersonRole model still has the title field.

After trying different options I managed to do this by using SimpleListFilter, and it was easier than I thought! I don't even need to define properties and such in the models.py. Here's the code, which goes into admin.py:

class PISchoolFilter(admin.SimpleListFilter):

   title = 'PI School'
   parameter_name = 'school'

   def lookups(self, request, model_admin):
        return (
                ('Arts & Humanities Admin',('Arts & Humanities Admin')),
    [...]
                )

   def queryset(self, request, queryset):
    if self.value() == 'Arts & Humanities Admin':
        return queryset.filter(
            person__personrole__person_role__contains="Principal investigator",
            person__personrole__person__school=5
        ).distinct()
    [...]
Back to Top