[Answer]-How to Customize Django Admin Filter

1👍

You must replace

return queryset.filter(book_type__id__exact=self.value()) 

by

return queryset.filter(book_type=self.value())

See https://docs.djangoproject.com/en/1.8/ref/models/querysets/#field-lookups for more information.

Also, in the lookups method, using:

types = model_admin.model.objects.distinct('book_type').values_list('book_type', flat=True)

would be much more efficient as you would not retrieve the whole data from the database to then filter it.

Edit:
I realized that the book_type field is a choice field.

First, the value passed to the choices argument must be

An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …] A being the value stored in the database, B a human readable value)

So passing a list of strings will fail.

Second, the Django admin’s default behaviour for such fields is exactly what you are trying to achieve so setting list_filter = ('book_type', ) in AdminInterpStore is enough.

👤aumo

Leave a comment