How to add search functionality to Django
Answered
34
I want to add a search feature to find articles by title or content.
A
Asked by
ahmed_tech
Platinum
•
151 rep
1 Answer
27
# 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)
S
Silver
•
222 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer