How to create Custom Django Admin List Filters?

How to create Custom Django Admin List Filters?

Effortlessly filter and organize your data with custom list filters in Django Admin

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:

# myapp/admin.py

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):
        # define the filter options
        return (
            ('option1', _('Option 1')),
            ('option2', _('Option 2')),
        )

    def queryset(self, request, queryset):
        # apply the filter to the 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]

# register the model with the custom filter
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.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!