How to filter and search on the Django admin page

The Django admin page is very useful if you are looking to search or filter the various aspects of your project.

For large-scale projects, the search and filter abilities allow for quick look-ups, faster updates, and increased efficiency.

Searching

Suppose we’ve already set up the Django admin index for our website.

Without incorporating the search and display features, the admin console merely shows us a list of all the users.

The index gives out very limited information, and there is no search bar to assist in searching users. This could be a major problem when dealing with several users.

To allow for searching and displaying more information, we must update the admin code by adding the following:

list_display = ('email', 'username', 'date_joined', 'last_login', 'is_admin', 'is_staff')

search_fields = ('email', 'username')

The fields associated with list_display will now be visible on the admin console for each user.

A search bar will also appear that will query the database for the fields associated with search_display.

We now have more information regarding users on the admin console. Further, we can easily search for users based on their username and emails.

Filtering

Searching is a useful feature. However, the Django framework does not know which field the element to be searched belongs to. To accommodate your search, it searches all the fields listed in search_fields. This is a slow and cumbersome process.

To overcome this issue, we can implement a ListFilter that will reduce the search space based on the filters that you choose to apply.

You can directly activate list filters like this:

list_filter = ('username',)

Note: This will activate list filters for existing models only.

Sometimes, our attributes only have a fixed number of categories. In such cases, we tend to bind options for the attributes to make them seem more intuitive.

Consider the case for the gender attribute.

We can add our filter like this:

choices_gender = [
    (0, 'male'),
    (1, 'female'),
]
Copyright ©2024 Educative, Inc. All rights reserved