Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for PostgreSQL to_tsvector function with multiple fields #885

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions django_filters/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from datetime import timedelta

from django import forms
from django.contrib.postgres.search import SearchVector
from django.db.models import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.sql.constants import QUERY_TERMS
Expand Down Expand Up @@ -53,6 +54,7 @@
'NumericRangeFilter',
'OrderingFilter',
'RangeFilter',
'SearchVectorFilter',
'TimeFilter',
'TimeRangeFilter',
'TypedChoiceFilter',
Expand Down Expand Up @@ -484,6 +486,18 @@ class TimeRangeFilter(RangeFilter):
field_class = TimeRangeField


class SearchVectorFilter(CharFilter):

def __init__(self, field_name=None, lookup_expr='exact', *, search_fields, **kwargs):
super().__init__(field_name, lookup_expr, **kwargs)
self.search_fields = search_fields

def filter(self, qs, value):
search_vectors = SearchVector(*self.search_fields)
query = {'%s__%s' % ('search_vector', self.lookup_expr): value}
return qs.annotate(search_vector=search_vectors).filter(**query)


class AllValuesFilter(ChoiceFilter):
@property
def field(self):
Expand Down
35 changes: 35 additions & 0 deletions tests/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
NumberFilter,
OrderingFilter,
RangeFilter,
SearchVectorFilter,
TimeRangeFilter,
TypedMultipleChoiceFilter
)
Expand Down Expand Up @@ -1586,6 +1587,40 @@ def test_fk_relation_attribute_on_m2m_relation(self):
pass


class SearchVectorFilterTest(TestCase):

def setUp(self):
from django.db import connection
if connection.vendor != 'postgresql':
self.skipTest('PostgreSQL backend needed to run this tests.')

def test_filtering(self):

u1 = User.objects.create(username='SpaceKitty99', first_name='Joe', last_name='Cox')
u2 = User.objects.create(username='Darth_vader', first_name='John', last_name='Doe')
u3 = User.objects.create(username='Kobza', first_name='Taras', last_name='Shevchenko')

class F(FilterSet):

person = SearchVectorFilter(field_name='first_name',
search_fields=['first_name', 'last_name'],
lookup_expr='icontains')

class Meta:
model = User
fields = ['person']

qs = User.objects.all()
f = F(queryset=qs)
self.assertQuerysetEqual(f.qs, [u1.pk, u2.pk, u3.pk], lambda o: o.pk, ordered=False)
f = F({'person': 'John'}, queryset=qs)
self.assertQuerysetEqual(f.qs, [u2.pk], lambda o: o.pk)
f = F({'person': 'oE'}, queryset=qs)
self.assertQuerysetEqual(f.qs, [u1.pk, u2.pk], lambda o: o.pk, ordered=False)
f = F({'person': 'bob'}, queryset=qs)
self.assertQuerysetEqual(f.qs, [])


class SymmetricalSelfReferentialRelationshipTests(TestCase):

def setUp(self):
Expand Down
25 changes: 25 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datetime import date, datetime, time, timedelta

from django import forms
from django.contrib.postgres.search import SearchVector
from django.test import TestCase, override_settings
from django.utils import translation
from django.utils.translation import ugettext as _
Expand Down Expand Up @@ -42,11 +43,13 @@
NumericRangeFilter,
OrderingFilter,
RangeFilter,
SearchVectorFilter,
TimeFilter,
TimeRangeFilter,
TypedMultipleChoiceFilter,
UUIDFilter
)

from tests.models import Book, User


Expand Down Expand Up @@ -1138,6 +1141,28 @@ def test_filtering_ignores_lookup_expr(self):
None__range=(datetime(2015, 4, 7, 8, 30), datetime(2015, 9, 6, 11, 45)))


class SearchVectorFilterTest(TestCase):

def setUp(self):
from django.db import connection
if connection.vendor != 'postgresql':
self.skipTest('PostgreSQL backend needed to run this tests.')

def test_default_field(self):
f = SearchVectorFilter(search_fields=['one', 'other'])
field = f.field
self.assertIsInstance(field, forms.CharField)

def test_filter(self):
search_fields = ['one', 'other']
qs = mock.Mock(spec=['annotate', 'annotate.filter()'])
f = SearchVectorFilter(search_fields=search_fields)
result = f.filter(qs, 'value')
qs.annotate.assert_called_once_with(search_vector=SearchVector(*search_fields))
qs.annotate().filter.assert_called_once_with(search_vector__exact='value')
self.assertNotEqual(qs, result)


class TimeRangeFilterTests(TestCase):

def test_default_field(self):
Expand Down