Hey everyone!
If you're using Django Admin to manage your project's data, you know that the ability to filter and organize your models is crucial. That's where list filters come in.

List filters are a built-in feature of Django Admin that allows you to narrow down the list of model instances based on certain criteria. By default, Django Admin provides filters for each model field, but you can also define custom filters to meet your specific needs.
To create a custom list filter, you'll need to define a subclass of SimpleListFilter and override the lookups and queryset methods.
Here's an example of how to do this:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
class MyCustomFilter(admin.SimpleListFilter):
title = _('custom filter')
parameter_name = 'custom_filter'
def lookups(self, request, model_admin):
return (
('option1', _('Option 1')),
('option2', _('Option 2')),
)
def queryset(self, request, queryset):
if self.value() == 'option1':
return queryset.filter(field1='value1')
if self.value() == 'option2':
return queryset.filter(field2='value2')
class MyModelAdmin(admin.ModelAdmin):
...
list_filter = [MyCustomFilter]
admin.site.register(MyModel, MyModelAdmin)
And that's it! You now have a custom list filter available in Django Admin.
Custom list filters are a great way to make it easier for users to find the data they need, so don't be afraid to experiment and see what works best for your project.
Happy coding!
Any thoughts? Write it down in the comments.
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.
Social Links