0 day streak
python / intermediate
Snippet

Django CBV ListView with Filtered QuerySet

ListViews are powerful Class-Based Views in Django that automatically render a list of objects. This example demonstrates how to override get_queryset() to filter articles by status and search query, combining multiple Q objects for flexible search functionality.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.views.generic import ListView
from django.db.models import Q
from .models import Article
class PublishedArticlesView(ListView):
model = Article
template_name = 'articles/list.html'
context_object_name = 'articles'
def get_queryset(self):
query = self.request.GET.get('q', '')
return Article.objects.filter(
status='published'
).filter(
Q(title__icontains=query) | Q(content__icontains=query)
).order_by('-published_at')
django
Breakdown
1
from django.views.generic import ListView
Import the ListView generic view class from Django's class-based views module
2
from django.db.models import Q
Import Q objects for building complex database queries with OR conditions
3
def get_queryset(self):
Override this method to customize which objects are retrieved from the database
4
Q(title__icontains=query) | Q(content__icontains=query)
Create a case-insensitive search filter across title AND content fields using Q object OR operator