34
I want to add a search feature to find articles by title or content.
Loading...
Q&A · Answered
I want to add a search feature to find articles by title or content.
Accepted answer
# 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)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.