Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Multi OR Operations

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading