Search and filter options help users find specific data quickly by typing keywords or choosing criteria.
Search and filter options in 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.
items = Item.objects.filter(category='Books')
items = Item.objects.filter(price__lte=20)
items = Item.objects.filter(name__icontains='phone')
items = Item.objects.filter(name__icontains=query, category=selected_category)This view gets optional search and category filters from the URL. It filters the Product list accordingly and sends it to the template.
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})
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.
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.
Practice
filter() do when used with icontains in a query?Solution
Step 1: Understand
Thefilter()usagefilter()method in Django ORM is used to select records that match certain conditions.Step 2: Understand
icontainslookupicontainschecks if a field contains a substring, ignoring case differences.Final Answer:
It returns records where the specified field contains the given substring, case-insensitive. -> Option AQuick Check:
filter() + icontains = case-insensitive substring search [OK]
- Confusing filter() with delete()
- Thinking icontains is case-sensitive
- Assuming filter() modifies data
- Mixing filter() with sorting methods
Book by title containing the word 'django' ignoring case?Solution
Step 1: Identify correct field lookup syntax
Django uses double underscores to separate field and lookup, sotitle__icontainsis correct.Step 2: Choose correct method for filtering multiple records
filter()returns a queryset;get()returns a single object and may error if multiple matches.Final Answer:
Book.objects.filter(title__icontains='django') -> Option DQuick Check:
filter() + __icontains syntax = Book.objects.filter(title__icontains='django') [OK]
- Using single underscore instead of double
- Using get() when multiple results expected
- Using contains instead of icontains for case-insensitive
- Using incorrect method names like contains
books contain if the URL query string is ?search=python?
def book_list(request):
query = request.GET.get('search', '')
books = Book.objects.filter(title__icontains=query)
return render(request, 'books.html', {'books': books})Solution
Step 1: Extract query parameter from request
The code gets the 'search' parameter from the URL query string, which is 'python'.Step 2: Apply filter with icontains lookup
The filter usestitle__icontains='python', so it returns books with titles containing 'python' ignoring case.Final Answer:
All Book objects with titles containing 'python' ignoring case. -> Option AQuick Check:
GET param + icontains filter = All Book objects with titles containing 'python' ignoring case. [OK]
- Thinking filter matches exact text only
- Assuming empty query returns all results
- Confusing GET params with POST data
- Believing filter ignores the query parameter
Product objects by a search term from the URL:
def product_search(request):
term = request.GET['search']
results = Product.objects.filter(name_icontains=term)
return render(request, 'search.html', {'results': results})Solution
Step 1: Check field lookup syntax in filter()
The code usesname_icontains, but Django requires double underscores between field and lookup:name__icontains.Step 2: Verify other parts of the code
Usingrequest.GET['search']is valid but may raise KeyError if missing; render() usage is correct with request parameter.Final Answer:
The field lookup should use double underscores:name__icontains. -> Option BQuick Check:
Field lookup syntax requires double underscores [OK]
- Using single underscore in field lookups
- Confusing filter() with get()
- Forgetting to pass request to render()
- Assuming request.GET[] never raises errors
Article objects by a search term in the title and also filters by a minimum number of views provided by the user. Which of the following code snippets correctly applies both filters using values from request.GET?Solution
Step 1: Extract and convert GET parameters safely
Usingget()with default values avoids errors. Convertingmin_viewsto int is necessary for numeric comparison.Step 2: Apply combined filters correctly
Usingfilter()with multiple conditions joined by commas applies AND logic.title__icontains=queryandviews__gte=min_viewscorrectly filter by title substring and minimum views.Final Answer:
query = request.GET.get('q', '') min_views = int(request.GET.get('min_views', 0)) articles = Article.objects.filter(title__icontains=query, views__gte=min_views) -> Option CQuick Check:
Safe GET + combined filter with AND = query = request.GET.get('q', '') min_views = int(request.GET.get('min_views', 0)) articles = Article.objects.filter(title__icontains=query, views__gte=min_views) [OK]
- Not converting min_views to int before filtering
- Using filter() then filter() with conflicting conditions
- Using contains instead of icontains for case-insensitive search
- Using exclude() incorrectly to simulate greater than or equal
Ready to prove it?
Pass the test and this pattern moves unknown
