×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS Roadmap
     ❯   

MODEL ADMIN

Adding Filters

Adding Filters

Filters in Django's admin interface enable users to refine the displayed records based on specific criteria, enhancing the data management experience.

Overview

By adding filters to your ModelAdmin class, you allow administrators to easily segment data and find records of interest without scrolling through large datasets.

Implementing Filters

To add filters to your admin model, use the list_filter attribute within your ModelAdmin class. Here’s a basic example:


from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_filter = ('status', 'created_at')

admin.site.register(MyModel, MyModelAdmin)

Components of Filters

  • Fields: The fields specified in the list_filter attribute will be displayed as filters in the admin interface. You can use fields of various types, such as CharField, DateField, or BooleanField.
  • Custom Filters: You can create custom filter classes by subclassing admin.SimpleListFilter for more complex filtering options.

Example of a Custom Filter

If you want to create a custom filter for a model, follow this example:


from django.contrib import admin
from .models import MyModel

class StatusFilter(admin.SimpleListFilter):
    title = 'Status'
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        return (
            ('active', 'Active'),
            ('inactive', 'Inactive'),
        )

    def queryset(self, request, queryset):
        if self.value() == 'active':
            return queryset.filter(status='active')
        if self.value() == 'inactive':
            return queryset.filter(status='inactive')
        return queryset

class MyModelAdmin(admin.ModelAdmin):
    list_filter = (StatusFilter,)

admin.site.register(MyModel, MyModelAdmin)

Conclusion

Adding filters to your ModelAdmin class significantly enhances the usability of the Django admin interface. By implementing standard and custom filters, you can provide a powerful tool for administrators to manage large datasets efficiently.


References


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2024 Nischal Lamichhane. All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.