Skip to content

Q&A · Answered

How to add search functionality to Django

asked 9 months, 1 week ago 535 views 1 answer
34

I want to add a search feature to find articles by title or content.

1 Answer

One accepted
27

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
# views.py
from django.db.models import Q

def search(request):
    query = request.GET.get('q', '')
    results = []
    
    if query:
        results = Article.objects.filter(
            Q(title__icontains=query) |
            Q(content__icontains=query) |
            Q(tags__name__icontains=query)
        ).distinct()
    
    return render(request, 'search.html', {
        'query': query,
        'results': results
    })

# For full-text search with PostgreSQL
from django.contrib.postgres.search import SearchVector

results = Article.objects.annotate(
    search=SearchVector('title', 'content')
).filter(search=query)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.