📝 Django

Search in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
89
🌳
Level
Advanced

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.

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 85
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 75

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!