2

I have QueryDict with list 'value': ['1', '2', '3', '4', '5'] - number of elements is unknown. I need convert this list to filter model using OR condition:

 Poll.objects.get(Q(value__icontains=option[0]) | Q(value__icontains=option[1]))

In SQL:

AND (value LIKE '%1%' OR value LIKE '%2%')

How to achieve this correct and easy way ?

2 Answers2

8

You can use the reduce operation to combine the Q objects.

Solution:

from functools import reduce
import operator
options = ['1', '2', '3', '4']

# uses operator or to combine the Q objects with the particular option filter
query = reduce(operator.or_, (Q(value__icontains=option) for option in options))

polls = Poll.objects.get(query)
Sachin
  • 3,576
  • 1
  • 15
  • 24
0

Poll.objects.get(value__in=['1', '2', '3', '4', '5']) should do it.

Or, for case insensitive query, see here: Django query case-insensitive list match

TeaPow
  • 687
  • 8
  • 17