Search and filter options help users find specific data quickly by typing keywords or choosing criteria.
0
0
Search and filter options in Django
Introduction
When you have a list of items like products or articles and want users to find one easily.
When users need to narrow down results by categories, dates, or other details.
When you want to improve user experience by avoiding long scrolling.
When you want to let users combine multiple filters to get precise results.
Syntax
Django
from django.shortcuts import render from .models import Item def item_list(request): query = request.GET.get('q') if query: items = Item.objects.filter(name__icontains=query) else: items = Item.objects.all() return render(request, 'items.html', {'items': items})
Use request.GET.get('q') to get the search term from the URL query.
filter(name__icontains=query) finds items where the name contains the search term, ignoring case.
Examples
Filter items to show only those in the 'Books' category.
Django
items = Item.objects.filter(category='Books')
Filter items with price less than or equal to 20.
Django
items = Item.objects.filter(price__lte=20)
Search items whose name contains 'phone' (case-insensitive).
Django
items = Item.objects.filter(name__icontains='phone')
Combine search and filter by category.
Django
items = Item.objects.filter(name__icontains=query, category=selected_category)Sample Program
This view gets optional search and category filters from the URL. It filters the Product list accordingly and sends it to the template.
Django
from django.shortcuts import render from .models import Product def product_list(request): search_term = request.GET.get('search') category_filter = request.GET.get('category') products = Product.objects.all() if search_term: products = products.filter(name__icontains=search_term) if category_filter: products = products.filter(category=category_filter) return render(request, 'products.html', {'products': products})
OutputSuccess
Important Notes
Always validate and sanitize user input to avoid errors or security issues.
Use icontains for case-insensitive search.
Combine multiple filters by chaining filter() calls or using multiple conditions in one call.
Summary
Search and filter help users find data quickly and easily.
Use Django's ORM filter() with field lookups like icontains for search.
Get search/filter values from request.GET and apply them to your query.