diff --git a/app/general/filters.py b/app/general/filters.py index 0ff668e0..ee85d366 100644 --- a/app/general/filters.py +++ b/app/general/filters.py @@ -1,7 +1,12 @@ import django_filters from django import forms -from django.contrib.postgres.search import SearchHeadline, SearchQuery, SearchRank -from django.db.models import F, Q +from django.contrib.postgres.search import ( + SearchHeadline, + SearchQuery, + SearchRank, + SearchVector, +) +from django.db.models import F, IntegerField, Q, Value from django_filters import ModelMultipleChoiceFilter, MultipleChoiceFilter from general.models import DocumentFile, Institution, Language, Project, Subject @@ -23,13 +28,6 @@ class DocumentFileFilter(django_filters.FilterSet): queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple ) - projects = django_filters.CharFilter(method="filter_projects", label="Projects") - # projects = django_filters.CharFilter( - # queryset=Project.objects.all(), - # method='filter_project', - # label="Projects" - # ) - class Meta: model = DocumentFile fields = [ @@ -43,24 +41,27 @@ def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) search = self.form.cleaned_data.get("search", "") + search_vector = SearchVector("title", weight="A") + SearchVector("description", weight="B") + + project_query = Project.objects.annotate( + search=SearchVector("name", weight="A") + SearchVector("description", weight="B") + ).filter(search=SearchQuery(search)) + queue = SearchQuery(search.strip()) search_rank = SearchRank(F("search_vector"), queue) search_headline = SearchHeadline("document_data", queue) queryset = ( queryset.annotate( + search=search_vector, rank=search_rank, search_headline=search_headline, + weight=Value(0, IntegerField()), ) .defer("document_data") .select_related("institution") ).order_by("-rank") - project_query = Project.objects.filter( - Q(name__icontains=search) | Q(description__icontains=search) - ) - - # Combine the two querysets into a single list - combined_results = list(queryset) + list(project_query) + combined_results = list(project_query) + list(queryset) return combined_results # return queryset @@ -72,9 +73,3 @@ def filter_search(self, queryset, name, value): else: return queryset - - def filter_projects(self, queryset, name, value): - if value: - projects = value.split(",") - return queryset.filter(projects__name__in=projects).distinct() - return queryset