0

I have for example the following lists:

list1 = ['blue', 'red']
list2 = ['green', 'yellow', 'black']

How could i create a query searching for all values (using postgresql).

This will work fine but it's hardcoded for only two values and therefore not handling the varying amount of values of the lists.

entry.objects.annotate(search=SearchVector('colors')).filter(search=SearchQuery('blue') | SearchQuery('red'))

I tried the following to create a 'search_query' string and place it in my query:

for c in color:
   search_string += "SearchQuery('" + c +"') | "

search_string = search_string[:-3]

This will result in the following search_strings

SearchQuery('blue') | SearchQuery('red')
SearchQuery('green') | SearchQuery('yellow') | SearchQuery('black')

If i now put this string in my query, it will not work.

entry.objects.annotate(search=SearchVector('colors')).filter(search=search_string)

I appreciate any help to solve this problem.

Link to django postgres search documentation: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/

fuser60596
  • 1,087
  • 1
  • 12
  • 26

2 Answers2

2

I don't know about postgreSQL but:

# Can run this query with SQL (i think django query auto convert for each type of DataBase???)
res = Models.Objects.filter(color__in = list1)
more_res = Models.Objects.filter( Q(color__in = list1) | Q(color__in = list2))

Django query basic (i don't know if it work for you???)

Nam Nguyễn
  • 552
  • 4
  • 20
1

Your search_string is not working because it is, well, a string.

You can use eval to make it work. Try this:

entry.objects.annotate(search=SearchVector('colors')).filter(search=eval(search_string))

It is not the best way though. Take a look at this

Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91