๐Ÿ“ Django

Search in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
279
๐ŸŒณ
Level
Advanced

You can start with simple Django ORM filters and move to PostgreSQL features when you need ranked, full-text search.

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

๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 561
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐Ÿ“

DRF Serializers

A serializer converts model objects to and from a Python dict and JSON.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 268

Did you like the article?

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