Requires PostgreSQL and django.contrib.postgres in INSTALLED_APPS.
Simple Search with icontains
def task_list(request):
q = request.GET.get('q', '')
tasks = Task.objects.filter(title__icontains=q) if q else Task.objects.all()
return render(request, 'tasks/list.html', {'tasks': tasks, 'q': q})
Search Across Multiple Fields
from django.db.models import Q
def task_list(request):
q = request.GET.get('q', '')
if q:
tasks = Task.objects.filter(
Q(title__icontains=q) |
Q(description__icontains=q) |
Q(owner__username__icontains=q)
)
else:
tasks = Task.objects.all()
return render(request, 'tasks/list.html', {'tasks': tasks, 'q': q})
Search Form in a Template
<form method="get" action="{% url 'task-list' %}">
<input type="text" name="q" value="{{ q }}" placeholder="Search tasks...">
<button type="submit">Search</button>
</form>
In a ListView
class TaskListView(ListView):
model = Task
template_name = 'tasks/list.html'
def get_queryset(self):
qs = super().get_queryset()
q = self.request.GET.get('q')
if q:
qs = qs.filter(
Q(title__icontains=q) | Q(description__icontains=q)
)
return qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['q'] = self.request.GET.get('q', '')
return context
Full-Text Search (PostgreSQL)
from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank
vector = SearchVector('title', weight='A') + SearchVector('description', weight='B')
query = SearchQuery(q)
tasks = Task.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.1).order_by('-rank')
Requires PostgreSQL and django.contrib.postgres in INSTALLED_APPS.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!