Full-text search using postgresql #162
@ -75,6 +75,7 @@ INSTALLED_APPS = [
|
||||
'django.contrib.staticfiles',
|
||||
'django.contrib.flatpages',
|
||||
'django.contrib.humanize',
|
||||
'django.contrib.postgres',
|
||||
'actstream',
|
||||
]
|
||||
|
||||
|
@ -1,6 +1,8 @@
|
||||
import logging
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.postgres.search import SearchQuery, SearchVector
|
||||
from django.db.models import Q
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.views.generic.list import ListView
|
||||
@ -89,16 +91,22 @@ class SearchView(ListedExtensionsView):
|
||||
_type = self._get_type_id_by_slug()
|
||||
queryset = queryset.filter(type=_type)
|
||||
if 'q' in self.request.GET:
|
||||
qs = self.request.GET['q'].split()
|
||||
search_query = Q()
|
||||
for token in qs:
|
||||
search_query &= (
|
||||
Q(slug__icontains=token)
|
||||
| Q(name__icontains=token)
|
||||
| Q(description__icontains=token)
|
||||
| Q(latest_version__tags__name__icontains=token)
|
||||
)
|
||||
queryset = queryset.filter(search_query).distinct()
|
||||
# using DEBUG as a shortcut for checking if we run on postgres vs sqlite
|
||||
if settings.DEBUG:
|
||||
qs = self.request.GET['q'].split()
|
||||
search_query = Q()
|
||||
for token in qs:
|
||||
search_query &= (
|
||||
Q(slug__icontains=token)
|
||||
| Q(name__icontains=token)
|
||||
| Q(description__icontains=token)
|
||||
| Q(latest_version__tags__name__icontains=token)
|
||||
)
|
||||
queryset = queryset.filter(search_query).distinct()
|
||||
else:
|
||||
query = SearchQuery(self.request.GET['q'], search_type='websearch')
|
||||
vector = SearchVector('slug', 'name', 'description', 'latest_version__tags__name')
|
||||
queryset = queryset.annotate(search=vector).filter(search=query).distinct()
|
||||
return queryset.prefetch_related(
|
||||
'authors',
|
||||
'latest_version__file',
|
||||
|
Loading…
Reference in New Issue
Block a user