This tutorial shows, how to build search view for your Django application with SearchVector class.
Why SearchQuery? SearchQuery translates the terms the user provides into a search query object that the database compares to a search vector. By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms (documentation).
1. Configure DATABASE dictionary for using PostgreSQL database management system in your project's settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'my_database',
'USER': 'database_user',
'PASSWORD': 'database_users_password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
2. Create url for search view in urls.py:
from django.urls import path
from .views import search_view
app_name = 'core'
urlpatterns = [
path('search/', search_view, name='search-view'),
]
3. Create the view itself. In views.py:
from blog.models import Article
from django.contrib.postgres.search import SearchVector
def search_view(request):
search_results = ''
query = ''
if request.method == 'POST':
query = request.POST.get('q')
search_results = Article.objects.annotate(search=SearchVector('title', 'content')).filter(search=query)
context = {'search_results': search_results}
return render(request, 'search.html', context)
4. Now create template named as search.html:
{% extends 'base.html' %}
{% load static %}
<form action="{% url 'core:search' %}" method="POST" enctype="multipart/form-data" novalidate autocomplete="off">
{% csrf_token %}
<input type="text" name="q" id="id_q" placeholder="Your search query here:">
<label for="id_q">Search query:</label>
<input type="submit" value="Search">
</form>