I am trying to do an OR operation for a specific group without knowing the number for each so that it is more than an OR LIKE
SELECT * FROM movies WHERE genres LIKE '%Action%' or genres LIKE '%Comedy%'
If we assume that I have genres added to it, how can I control the genre so that more than one OR can be chosen for genres without knowing how many genres will be entered?
Like Example
User input Genres: [Action, Comedy, Horror]
as we can see user add new Genres Horror
so, my query Muse be
SELECT * FROM movies WHERE genres LIKE '%Action%' or genres LIKE '%Comedy%' or genres LIKE '%Horror%'
My Simple Script
series = series_db.objects.filter(Q(genres__icontains='Action') | Q(genres__icontains='Comedy'),
status=1
).values('id','title')
>Solution :
You can build a Q object dynamically:
from operator import or_
from functools imoprt reduce
genres = ["Action", "Comedy", "Horror"]
q = reduce(or_, (Q(genres__icontains=g) for g in genres))
# ...
qs = qs.filter(q)
This is a shortcut for:
q = Q(genres__icontains=genres[0])
for g in genres[1:]:
q |= Q(genres__icontains=g)