Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django SearchVector using icontains

I am trying to search for a list of values in multiple columns in postgres (via django). I was able to use SearchQuery and SearchVector and this works great if one of the search values matches a full word. I was hoping to use icontains so that partial strings could also be used in the search. Is this possible and if so could someone point me in the right direction. Here is an example of my approach below.

Example Data:

Superhero.objects.create(
    superhero='Batman',
    publisher='DC Comics', 
    alter_ego='Bruce Wayne',
)
Superhero.objects.create(
    superhero='Hulk',
    publisher='Marvel Comics',
    alter_ego='Bruce Banner',
)

Django filter:

from django.contrib.postgres.search import SearchQuery, SearchVector

query = SearchQuery('man') | SearchQuery('Bruce') 
vector = SearchVector('superhero', 'alter_ego', 'publisher')
queryset = queryset.annotate(search=vector).filter(search=query)

This would return the Hulk record but I am hoping I can somehow use like 'icontains' so that when searching for 'man' the Batman record would also be returned. Any help is appreciated!

like image 269
Jimmy Arroyo Avatar asked Apr 16 '18 22:04

Jimmy Arroyo


2 Answers

You can apply icontains to the filter like:

queryset = queryset.annotate(search=vector).filter(search__icontains=query)
like image 157
Michel Rugenbrink Avatar answered Nov 12 '22 14:11

Michel Rugenbrink


So SearchQuery and SearchVector are a part of Django's Full Text searching functionality and it doesnt look like you can achieve what I was wanting to do with these functions. I have taken a different approach thanks to Julian Phalip's approach here.. https://www.julienphalip.com/blog/adding-search-to-a-django-site-in-a-snap/

like image 26
Jimmy Arroyo Avatar answered Nov 12 '22 14:11

Jimmy Arroyo