3👍
✅
Here is one way to do it explicitly:
>>> Q_filter = Q()
>>> for value in rows_to_search:
... Q_filter |= Q(**{"{}__iregex".format(value): search})
Here is one-liner using reduce()
:
>>> Q_filter = reduce(lambda x, y: x | Q(**{"{}__iregex".format(y): search}), rows_to_search, Q())
Another one-liner using operator.or_
with list comprehensions:
>>> Q_filter = reduce(operator.or_, [Q(**{"{}__iregex".format(key): search}) for key in rows_to_search])
Then you can call the query as follows:
MyModel.objects.filter(Q_filter)
Source:stackexchange.com