10

Is there a way to take a list of django query expresses (e.g. Q(first_name="Jordan"), where Q is django.db.models.Q) and bitwise OR them together?

In other words, I have something like this:

search_string = "various search terms"

And I want to do this:

search_params = [Q(description__icontains=term) for term in re.split(r'\W', search_string)]
search_params = something_magical(search_params)
results = Record.objects.filter(search_params)

where search_params now is equivalent to Q(description__icontains="various") | Q(description__icontains="search" | Q(description__icontains="terms"

I know it would be possible with a function like this:

def something_magical(lst):
    result = lst[0]
    for l in lst[1:]
        result |= l
    return result

So I'm wondering if this functionality is already built into Python (and I'm assuming it's more optimized than my function here).

Although I'm interested in it for this application, I'm also just interested in it theoretically.

2
  • I don't think there is such an django operator...But you could just do all the "or" queries and then use python set operators to combine the results ? ( docs.python.org/library/sets.html#set-objects ) Commented Jan 17, 2012 at 23:44
  • @RichardGreen that can create pretty ugly queries Commented Jan 18, 2012 at 1:07

1 Answer 1

19

You probably want

import operator 
from functools import reduce    # Python 3
search_params = reduce(operator.or_, search_params, Q())

This will place a bit-wise or (|) between all the items in search_params, starting with an empty condition Q().

Sign up to request clarification or add additional context in comments.

4 Comments

Nice! Things like this make my love python more and more.
Just spent a little while playing with reduce and map.
Great you like it! You'll probably also enjoy itertools then.
Very smart. Did not know about operators as functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.