django admin filter_list by manytomany filed

Viewed 84

models.py

class Author(models.Model):
    nickname = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=255)
    authors = models.ManyToManyField(Author)

admin.py

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_filter = (???,)

How to filter the books of a particular author through the admin panel.

1 Answers

You can look "through" relations with double underscores, so you can filter on the nickname of the authors of that book with:

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_filter = ('authors__nickname',)

or as specified in the documentation of list_filter:

(…)

Field names in list_filter can also span relations using the __ lookup, (…)

Related